Ejemplo n.º 1
0
        /// <summary>Call this method in Loaded event as the event will be automatically 
        /// deregistered when the FrameworkElement has been unloaded. </summary>
        public static void RegisterBackKey(Page page)
        {
            var callback = new TypedEventHandler<CoreDispatcher, AcceleratorKeyEventArgs>(
                delegate(CoreDispatcher sender, AcceleratorKeyEventArgs args)
                {
                    if (!args.Handled && args.VirtualKey == VirtualKey.Back &&
                        (args.EventType == CoreAcceleratorKeyEventType.KeyDown || 
                            args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown))
                    {
                        var element = FocusManager.GetFocusedElement();
                        if (element is FrameworkElement && PopupHelper.IsInPopup((FrameworkElement)element))
                            return;

                        if (element is TextBox || element is PasswordBox || element is WebView)
                            return; 

                        if (page.Frame.CanGoBack)
                        {
                            args.Handled = true;
                            page.Frame.GoBack();
                        }
                    }
                });

            page.Dispatcher.AcceleratorKeyActivated += callback;

            SingleEvent.RegisterEvent(page,
                (p, h) => p.Unloaded += h,
                (p, h) => p.Unloaded -= h,
                (o, a) => { page.Dispatcher.AcceleratorKeyActivated -= callback; });
        }
Ejemplo n.º 2
0
 public GeofencingService(TypedEventHandler<GeofenceMonitor, object> stateChange, TypedEventHandler<GeofenceMonitor, object> statusChanged, CoreDispatcher dispatcher)
 {
     Messenger.Default.Register<SetupGeofencingMessage>(this, async message => await SetupGeofencesAsync(message));
     this.stateChange = stateChange;
     this.statusChanged = statusChanged;
     this.dispatcher = dispatcher;
 }
        /// <summary>
        /// Constructor initializes necessary variables and reads in saved constraints from text file.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            string fileName = @"Stored_Constraints.txt";
            Debug.WriteLine(DateTime.Now.ToString());
            filePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), fileName);
            dateTimesForConstraints = new Dictionary<string, string>();

            backgroundListener = new SpeechRecognizer();
            constraints = new List<string>();
            BLResultGenerated = new TypedEventHandler<SpeechContinuousRecognitionSession, SpeechContinuousRecognitionResultGeneratedEventArgs>(blResultGenerated);
            backgroundListener.ContinuousRecognitionSession.ResultGenerated += BLResultGenerated;

            constraints = readInConstraintsFromFile();
            currentlyStoredConstraints = constraints.ToList();
            updateConstraintsWindow(constraints);

            this.Closing += OnAppClosing;

            var waitOn = loadOnStart();
            while (waitOn.Status != AsyncStatus.Completed) { }
            var ff = backgroundListener.ContinuousRecognitionSession.StartAsync();

            notifyIcon = new NotifyIcon();
            notifyIcon.Icon = new System.Drawing.Icon("trayImage.ico");
            notifyIcon.Visible = true;
            notifyIcon.DoubleClick +=
                delegate (object sender, EventArgs args)
                {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                };
        }
Ejemplo n.º 4
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            object apiKey = null;

            if (Windows.Storage.ApplicationData.Current.RoamingSettings.Values.TryGetValue("FlickrApiKey", out apiKey))
            {
                FlickrApiKey.Text = (string)apiKey;
            }

            object username = null;

            if (Windows.Storage.ApplicationData.Current.RoamingSettings.Values.TryGetValue("FlickrUsername", out username))
            {
                FlickrUsername.Text = (string)username;
            }

            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentOrientation(this);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DbControllerQueryAttributeChecker"/> class.
        /// </summary>
        /// <param name="missingAttributeHandler">The event handler for types with missing attributes.
        /// Cannot be null.</param>
        /// <exception cref="ArgumentNullException"><paramref name="missingAttributeHandler"/> is null.</exception>
        /// <param name="typesToIgnore">Optional array of types to ignore. If a type is in this collection, it will
        /// never be invoked by the <paramref name="missingAttributeHandler"/>.</param>
        public DbControllerQueryAttributeChecker(
            TypedEventHandler<DbControllerQueryAttributeChecker, EventArgs<Type>> missingAttributeHandler,
            params Type[] typesToIgnore)
        {
            if (missingAttributeHandler == null)
                throw new ArgumentNullException("missingAttributeHandler");

            _missingAttributeHandler = missingAttributeHandler;
            _typesToIgnore = typesToIgnore;

            var filter = new TypeFilterCreator
            {
                IsClass = true,
                IsAbstract = false,
                IsInterface = false,
                RequireAttributes = false,
                Interfaces = new Type[] { typeof(IDbQuery) },
                MatchAllInterfaces = true,
                RequireInterfaces = false,
                RequireConstructor = false,
                IsEnum = false
            };

            new TypeFactory(filter.GetFilter(), LoadTypeHandler);
        }
Ejemplo n.º 6
0
		public MainPage()
		{
			this.InitializeComponent();
			NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;

			AppCallbacks appCallbacks = AppCallbacks.Instance;
			// Setup scripting bridge
			_bridge = new WinRTBridge.WinRTBridge();
			appCallbacks.SetBridge(_bridge);

			appCallbacks.RenderingStarted += () => { RemoveSplashScreen(); };

#if !UNITY_WP_8_1
			appCallbacks.SetKeyboardTriggerControl(this);
#endif
			appCallbacks.SetSwapChainPanel(GetSwapChainPanel());
			appCallbacks.SetCoreWindowEvents(Window.Current.CoreWindow);
			appCallbacks.InitializeD3DXAML();

			splash = ((App)App.Current).splashScreen;
			GetSplashBackgroundColor();
			OnResize();
			onResizeHandler = new WindowSizeChangedEventHandler((o, e) => OnResize());
			Window.Current.SizeChanged += onResizeHandler;

#if UNITY_WP_8_1
			onRotationChangedHandler = new TypedEventHandler<DisplayInformation, object>((di, o) => { OnRotate(di); });
			ExtendedSplashImage.RenderTransformOrigin = new Point(0.5, 0.5);
			var displayInfo = DisplayInformation.GetForCurrentView();
			displayInfo.OrientationChanged += onRotationChangedHandler;
			OnRotate(displayInfo);

			SetupLocationService();
#endif
		}
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GroupManager"/> class.
        /// </summary>
        /// <param name="tryCreateGroup">A func that is used to create a group started by
        /// an <see cref="IGroupable"/>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="tryCreateGroup"/> is null.</exception>
        public GroupManager(Func<IGroupManager, IGroupable, IGroup> tryCreateGroup)
        {
            if (tryCreateGroup == null)
                throw new ArgumentNullException("tryCreateGroup");

            _groupDisbandHandler = Group_Disbanded;
            _tryCreateGroup = tryCreateGroup;
        }
Ejemplo n.º 8
0
 /// <summary>Call this method in Loaded event as the event will be automatically 
 /// deregistered when the FrameworkElement has been unloaded. </summary>
 /// <param name="page">The page. </param>
 /// <param name="handler">The event handler. </param>
 public static void RegisterAcceleratorKeyActivated(FrameworkElement page, TypedEventHandler<CoreDispatcher, AcceleratorKeyEventArgs> handler)
 {
     page.Dispatcher.AcceleratorKeyActivated += handler;
     SingleEvent.RegisterEvent(page, (p, h) => p.Unloaded += h, (p, h) => p.Unloaded -= h, (o, a) =>
     {
         page.Dispatcher.AcceleratorKeyActivated -= handler;
     });
 }
Ejemplo n.º 9
0
		private static void OnProviderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var searchBox = (SearchBox)d;
			CleanSuggestionRequestedEventHandlers(searchBox);
			var eventHandler = new TypedEventHandler<SearchBox, SearchBoxSuggestionsRequestedEventArgs>(searchBox_SuggestionsRequested);
			_suggestionRequestedEventHandlers.Add(searchBox, eventHandler);
			searchBox.SuggestionsRequested += eventHandler;
		}
Ejemplo n.º 10
0
    public MainPage()
    {
      InitializeComponent();

      NavigationCacheMode = NavigationCacheMode.Required;
      m_mediaPropertyChanged += SystemMediaControls_PropertyChanged;

      //Init();
    }
Ejemplo n.º 11
0
        /*public static class myGlobals
        {
            public static int procNum { get; private set; }

            public static void newProc(int i)
            {
                procNum = i;
            }
        }*/
      
        public MainPage()
        {
            this.InitializeComponent();
            InitSettings();
            m_mediaPropertyChanged = new TypedEventHandler<SystemMediaTransportControls, SystemMediaTransportControlsPropertyChangedEventArgs>(SystemMediaControls_PropertyChanged);
            EnumerateWebcamsAsync();
            startDevice();
            showCam();
        }
Ejemplo n.º 12
0
 private void RegisterShaken()
 {
     shakenHandler = new TypedEventHandler<Accelerometer, AccelerometerShakenEventArgs>(OnShaken);
     accelerometer = Accelerometer.GetDefault();
     if (accelerometer != null)
     {
         accelerometer.Shaken += shakenHandler;
     }
 }
 private void Page_Loaded(object sender, RoutedEventArgs e)
 {
     if (_displayHandler == null)
     {
         _displayHandler = Page_OrientationChanged;
         _layoutHandler = Page_LayoutChanged;
     }
     DisplayProperties.OrientationChanged += _displayHandler;
     ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
     SetCurrentViewState(this);
 }
Ejemplo n.º 14
0
 public static void SendToastWithActionNotification(string toastXML, TypedEventHandler<ToastNotification, System.Object> toastActived)
 {
     Windows.Data.Xml.Dom.XmlDocument badgeDOM = new Windows.Data.Xml.Dom.XmlDocument();
     badgeDOM.LoadXml(toastXML);
     ToastNotification toast = new ToastNotification(badgeDOM);
     if (toastActived != null)
     {
         toast.Activated += toastActived;
     }
     ToastNotificationManager.CreateToastNotifier().Show(toast);
 }
Ejemplo n.º 15
0
        public static void Show(
            string title, 
            string message = null,
            string furtherMessage = null,
            TypedEventHandler<ToastNotification, object> onActivate = null,
            TypedEventHandler<ToastNotification, ToastDismissedEventArgs> onDismiss = null)
        {
            // Get a toast XML template
            var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);

            // Fill in the text elements
            var stringElements = toastXml.GetElementsByTagName("text");

            var textIndex = 0;
            //Add the title
            stringElements[textIndex].AppendChild(toastXml.CreateTextNode(title));
            textIndex++;

            //Add the message
            if (!string.IsNullOrEmpty(message))
            {
                stringElements[textIndex].AppendChild(toastXml.CreateTextNode(message));
                textIndex++;
            }

            //Add the further message
            if (!string.IsNullOrEmpty(furtherMessage))
            {
                stringElements[textIndex].AppendChild(toastXml.CreateTextNode(furtherMessage));
            }

            // Specify the absolute path to an image
            var imagePath = "file:///" + Path.GetFullPath("Resources/logo_512.png");
            var imageElements = toastXml.GetElementsByTagName("image");
            var namedItem = imageElements[0].Attributes.GetNamedItem("src");

            if (namedItem != null)
                namedItem.NodeValue = imagePath;

            var toast = new ToastNotification(toastXml);

            if (onActivate != null)
            {
                toast.Activated += onActivate;
            }

            if (onDismiss != null)
            {
                toast.Dismissed += onDismiss;
            }

            ToastNotificationManager.CreateToastNotifier(AppId).Show(toast);
        }
        public MainWindow()
        {
            InitializeComponent();

            recognizer = new SpeechRecognizer();
            List<String> constraints = new List<string>();
            //recognizer.Constraints.Add(new SpeechRecognitionListConstraint(constraints));
            IAsyncOperation<SpeechRecognitionCompilationResult> op = recognizer.CompileConstraintsAsync();
            resultGenerated = new TypedEventHandler<SpeechContinuousRecognitionSession, SpeechContinuousRecognitionResultGeneratedEventArgs>(UpdateTextBox);
            recognizer.ContinuousRecognitionSession.ResultGenerated += resultGenerated;
            OnStateChanged = new TypedEventHandler<SpeechRecognizer, SpeechRecognizerStateChangedEventArgs>(onStateChanged);
            recognizer.StateChanged += OnStateChanged;
            op.Completed += HandleCompilationCompleted;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Targeter"/> class.
        /// </summary>
        /// <param name="world">The world.</param>
        /// <exception cref="ArgumentNullException"><paramref name="world"/> is <c>null</c>.</exception>
        protected Targeter(World world)
        {
            if (world == null)
                throw new ArgumentNullException("world");

            _world = world;

            _mouseOverBeforeDrawHandler = MouseOver_BeforeDraw;
            _mouseOverBeforeDrawHandler = MouseOver_BeforeDraw;
            _mouseOverAfterDrawHandler = MouseOver_AfterDraw;
            _targetBeforeDrawHandler = Target_BeforeDraw;
            _targetAfterDrawHandler = Target_AfterDraw;

            _world.MapChanged += World_MapChanged;
        }
Ejemplo n.º 18
0
        public ScannerPage()
        {


            InitializeComponent();

            int ver = Scanner.MWBgetLibVersion();
            int v1 = (ver >> 16);
            int v2 = (ver >> 8) & 0xff;
            int v3 = (ver & 0xff);
            libVersion = String.Format("{0}.{1}.{2}", v1, v2, v3);

            System.Diagnostics.Debug.WriteLine("Lib version: " + libVersion);

            processingHandler = new DoWorkEventHandler(bw_DoWork);
            previewFrameHandler = new TypedEventHandler<ICameraCaptureDevice, Object>(cam_PreviewFrameAvailable);

            bw.WorkerReportsProgress = false;
            bw.WorkerSupportsCancellation = true;

            bw.DoWork += processingHandler;

        }
Ejemplo n.º 19
0
 private void DetachEvent(TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs> ev)
 {
     _accelero.ReportInterval = 0;
     _accelero.ReadingChanged -= ev;
 }
Ejemplo n.º 20
0
 private void DetachEvent(TypedEventHandler <Accelerometer, AccelerometerReadingChangedEventArgs> ev)
 {
     _accelero.ReportInterval  = 0;
     _accelero.ReadingChanged -= ev;
 }
Ejemplo n.º 21
0
 public void RegisterSearchQueryHandler(TypedEventHandler <SearchPane, SearchPaneQuerySubmittedEventArgs> handler)
 {
     SearchPane.GetForCurrentView().QuerySubmitted += handler;
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
 /// </summary>
 /// <param name="e">
 /// Event data that can be examined by overriding code. The event data is representative
 /// of the navigation that will unload the current Page unless canceled. The
 /// navigation can potentially be canceled by setting Cancel.
 /// </param>
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     base.OnNavigatingFrom(e);
     applicationData.DataChanged -= dataChangedHandler;
     dataChangedHandler           = null;
 }
Ejemplo n.º 23
0
        async void OnPageActionSheet(Page sender, ActionSheetArguments options)
        {
            List <string> buttons = options.Buttons.ToList();

            var list = new Windows.UI.Xaml.Controls.ListView
            {
                Style              = (Windows.UI.Xaml.Style)Windows.UI.Xaml.Application.Current.Resources["ActionSheetList"],
                ItemsSource        = buttons,
                IsItemClickEnabled = true
            };

            var dialog = new ContentDialog
            {
                Template = (Windows.UI.Xaml.Controls.ControlTemplate)Windows.UI.Xaml.Application.Current.Resources["MyContentDialogControlTemplate"],
                Content  = list,
                Style    = (Windows.UI.Xaml.Style)Windows.UI.Xaml.Application.Current.Resources["ActionSheetStyle"]
            };

            if (options.Title != null)
            {
                dialog.Title = options.Title;
            }

            list.ItemClick += (s, e) =>
            {
                dialog.Hide();
                options.SetResult((string)e.ClickedItem);
            };

            TypedEventHandler <CoreWindow, CharacterReceivedEventArgs> onEscapeButtonPressed = delegate(CoreWindow window, CharacterReceivedEventArgs args)
            {
                if (args.KeyCode == 27)
                {
                    dialog.Hide();
                    options.SetResult(ContentDialogResult.None.ToString());
                }
            };

            Window.Current.CoreWindow.CharacterReceived += onEscapeButtonPressed;

            _actionSheetOptions = options;

            if (options.Cancel != null)
            {
                dialog.SecondaryButtonText = options.Cancel;
            }

            if (options.Destruction != null)
            {
                dialog.PrimaryButtonText = options.Destruction;
            }

            ContentDialogResult result = await dialog.ShowAsync();

            if (result == ContentDialogResult.Secondary)
            {
                options.SetResult(options.Cancel);
            }
            else if (result == ContentDialogResult.Primary)
            {
                options.SetResult(options.Destruction);
            }

            Window.Current.CoreWindow.CharacterReceived -= onEscapeButtonPressed;
        }
 /// <summary>
 /// Use to invoke an async <see cref="TypedEventHandler{TSender, TResult}"/> using <see cref="DeferredEventArgs"/>.
 /// </summary>
 /// <typeparam name="S">Type of sender.</typeparam>
 /// <typeparam name="R"><see cref="EventArgs"/> type.</typeparam>
 /// <param name="eventHandler"><see cref="TypedEventHandler{TSender, TResult}"/> to be invoked.</param>
 /// <param name="sender">Sender of the event.</param>
 /// <param name="eventArgs"><see cref="EventArgs"/> instance.</param>
 /// <returns><see cref="Task"/> to wait on deferred event handler.</returns>
 public static Task InvokeAsync <S, R>(this TypedEventHandler <S, R> eventHandler, S sender, R eventArgs)
     where R : DeferredEventArgs
 {
     return(InvokeAsync(eventHandler, sender, eventArgs, CancellationToken.None));
 }
Ejemplo n.º 25
0
        protected override void OnBackRequestedOverride(object sender, HandledEventArgs e)
        {
            if (!_wasFullScreen)
            {
                ApplicationView.GetForCurrentView().ExitFullScreenMode();
            }

            if (ViewModel != null)
            {
                ViewModel.Aggregator.Unsubscribe(this);

                ViewModel.Delegate = null;
                ViewModel.Items.CollectionChanged -= OnCollectionChanged;

                Bindings.StopTracking();
            }

            //var container = GetContainer(0);
            //var root = container.Presenter;
            if (ViewModel != null && ViewModel.SelectedItem == ViewModel.FirstItem && _closing != null)
            {
                ScrollingHost.Opacity = 0;
                Preview.Opacity       = 1;

                var root = Preview.Presenter;

                var animation = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("FullScreenPicture", root);
                if (animation != null)
                {
                    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimation", "Configuration"))
                    {
                        animation.Configuration = new BasicConnectedAnimationConfiguration();
                    }

                    var element = _closing();
                    if (element.ActualWidth > 0 && animation.TryStart(element))
                    {
                        TypedEventHandler <ConnectedAnimation, object> handler = null;
                        handler = (s, args) =>
                        {
                            animation.Completed -= handler;
                            Hide();
                        };

                        animation.Completed += handler;
                    }
                    else
                    {
                        Hide();
                    }
                }
                else
                {
                    Hide();
                }
            }
            else
            {
                var batch = _layout.Compositor.CreateScopedBatch(CompositionBatchTypes.Animation);

                _layout.StartAnimation("Offset.Y", CreateScalarAnimation(_layout.Offset.Y, (float)ActualHeight));

                batch.End();
                batch.Completed += (s, args) =>
                {
                    ScrollingHost.Opacity = 0;
                    Preview.Opacity       = 1;

                    Hide();
                };
            }

            _layer.StartAnimation("Opacity", CreateScalarAnimation(1, 0));

            if (Transport.IsVisible)
            {
                Transport.Hide();
            }

            Unload();
            Dispose();

            e.Handled = true;
        }
Ejemplo n.º 26
0
 public void AddValueChangedCallback(GattCharacteristic characteristic, TypedEventHandler <GattCharacteristic, GattValueChangedEventArgs> callback)
 {
     this.callbacks[characteristic.AttributeHandle] = callback;
     characteristic.ValueChanged += callback;
 }
Ejemplo n.º 27
0
        //>>

        //<< Playlist management functions and handlers
        /// <summary>
        /// Start playlist and change UVC state
        /// </summary>
        void StartPlayback()
        {
            try
            {
                if (playbackStartedPreviously)                 // If playback was already started once we can just resume playing.
                {
                    BackgroundMediaPlayer.Current.Play();
                }
                else
                {
                    playbackStartedPreviously = true;

                    var currentTrackId = AppSettingsHelper.ReadVal(ApplicationSettingsConstants.TrackId);                     // If the task was cancelled we would have saved the current track and its position. We will try playback from there.
                    if (currentTrackId == null)
                    {
                        BackgroundMediaPlayer.Current.Play();
                    }
                    else
                    {
                        Debug.WriteLine($"**>Getting {currentTrackId}     from:"); _mpl.Items.ToList().ForEach(r => Debug.WriteLine($"**>        {GetTrackId(r)}"));

                        var index = _mpl.Items.ToList().FindIndex(item => GetTrackId(item).ToString() == (string)currentTrackId);                         // Find the index of the item by name

                        var currentTrackPosition = AppSettingsHelper.ReadVal(ApplicationSettingsConstants.Position);
                        if (currentTrackPosition == null)
                        {
                            Debug.WriteLine("StartPlayback: Switching to track " + index);                             // Play from start if we dont have position
                            _mpl.MoveTo((uint)index);

                            BackgroundMediaPlayer.Current.Play();
                        }
                        else
                        {
                            // Play from exact position otherwise
                            TypedEventHandler <MediaPlaybackList, CurrentMediaPlaybackItemChangedEventArgs> handler = null;
                            handler = (MediaPlaybackList list, CurrentMediaPlaybackItemChangedEventArgs args) =>
                            {
                                if (args.NewItem == _mpl.Items[index])
                                {
                                    // Unsubscribe because this only had to run once for this item
                                    _mpl.CurrentItemChanged -= handler;

                                    // Set position
                                    var position = TimeSpan.Parse((string)currentTrackPosition);
                                    Debug.WriteLine("StartPlayback: Setting Position " + position);
                                    BackgroundMediaPlayer.Current.Position = position;

                                    BackgroundMediaPlayer.Current.Play();
                                }
                            };
                            _mpl.CurrentItemChanged += handler;

                            Debug.WriteLine("StartPlayback: Switching to track " + index);                             // Switch to the track which will trigger an item changed event
                            playbackStartedPreviously = false;
                            _mpl.MoveTo((uint)index);
                            playbackStartedPreviously = true;
                        }
                    }
                }
            }
            catch (Exception ex) { Debug.WriteLine($"$#~>{ex.Message}"); if (Debugger.IsAttached)
                                   {
                                       Debugger.Break();
                                   }                                                                                            /*else throw;*/
                                   MessageService.SendMessageToForeground(new ExceptionCaughtMessage(ex.Message)); }
        }
Ejemplo n.º 28
0
        private Task <bool> clearConfirm()
        {
            var tsk = new TaskCompletionSource <bool>();
            TypedEventHandler <ContentDialog, ContentDialogButtonClickEventArgs> yes = null, no = null;

            yes = (o, a) =>
            { tsk.SetResult(true); cfmDlg.PrimaryButtonClick -= yes; cfmDlg.SecondaryButtonClick -= no; };
            no = (o, a) =>
            { tsk.SetResult(false); cfmDlg.PrimaryButtonClick -= yes; cfmDlg.SecondaryButtonClick -= no; };
            cfmDlg.PrimaryButtonClick   += yes;
            cfmDlg.SecondaryButtonClick += no;
            cfmDlg.ShowAsync();
            return(tsk.Task);
        }
Ejemplo n.º 29
0
    /// <summary>
    /// This is just one big lump of code right now which should be factored out into some kind of
    /// 'frame reader' class which can then be subclassed for depth frame and video frame but
    /// it was handy to have it like this while I experimented with it - the intention was
    /// to tidy it up if I could get it doing more or less what I wanted :-)
    /// </summary>
    async Task ProcessingLoopAsync()
    {
        var depthMediaCapture = await this.GetMediaCaptureForDescriptionAsync(
            MediaFrameSourceKind.Depth, 448, 450, 15);

        var depthFrameReader = await depthMediaCapture.Item1.CreateFrameReaderAsync(depthMediaCapture.Item2);

        depthFrameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime;

        MediaFrameReference lastDepthFrame = null;

        long  depthFrameCount          = 0;
        float centrePointDepthInMetres = 0.0f;

        // Expecting this to run at 1fps although the API (seems to) reports that it runs at 15fps
        TypedEventHandler <MediaFrameReader, MediaFrameArrivedEventArgs> depthFrameHandler =
            (sender, args) =>
        {
            using (var depthFrame = sender.TryAcquireLatestFrame())
            {
                if ((depthFrame != null) && (depthFrame != lastDepthFrame))
                {
                    lastDepthFrame = depthFrame;

                    Interlocked.Increment(ref depthFrameCount);

                    // Always try to grab the depth value although, clearly, this is subject
                    // to a bunch of race conditions etc. as other thread access it.
                    centrePointDepthInMetres =
                        GetDepthValueAtCoordinate(depthFrame,
                                                  (int)(depthFrame.Format.VideoFormat.Width * MAGIC_DEPTH_FRAME_WIDTH_RATIO_CENTRE),
                                                  (int)(depthFrame.Format.VideoFormat.Height * MAGIC_DEPTH_FRAME_HEIGHT_RATIO_CENTRE)) ?? 0.0f;
                }
            }
        };

        long rgbProcessedCount = 0;
        long facesPresentCount = 0;
        long rgbDroppedCount   = 0;

        MediaFrameReference lastRgbFrame = null;

        var faceBitmapFormats = FaceTracker.GetSupportedBitmapPixelFormats().Select(
            format => format.ToString().ToLower()).ToArray();

        var faceTracker = await FaceTracker.CreateAsync();

        var rgbMediaCapture = await this.GetMediaCaptureForDescriptionAsync(
            MediaFrameSourceKind.Color, 1280, 720, 30, faceBitmapFormats);

        var rgbFrameReader = await rgbMediaCapture.Item1.CreateFrameReaderAsync(rgbMediaCapture.Item2);

        rgbFrameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime;

        int busyProcessingRgbFrame = 0;

        var unityWorldCoordinateSystem =
            Marshal.GetObjectForIUnknown(WorldManager.GetNativeISpatialCoordinateSystemPtr()) as SpatialCoordinateSystem;

        // Expecting this to run at 30fps.
        TypedEventHandler <MediaFrameReader, MediaFrameArrivedEventArgs> rgbFrameHandler =
            (sender, args) =>
        {
            // Only proceed if we're not already 'busy' - i.e. we'
            if (Interlocked.CompareExchange(ref busyProcessingRgbFrame, 1, 0) == 0)
            {
                Task.Run(
                    async() =>
                {
                    using (var rgbFrame = rgbFrameReader.TryAcquireLatestFrame())
                    {
                        if ((rgbFrame != null) && (rgbFrame != lastRgbFrame))
                        {
                            ++rgbProcessedCount;

                            lastRgbFrame     = rgbFrame;
                            var facePosition = uVector3.zero;

                            using (var videoFrame = rgbFrame.VideoMediaFrame.GetVideoFrame())
                            {
                                var faces     = await faceTracker.ProcessNextFrameAsync(videoFrame);
                                var firstFace = faces.FirstOrDefault();

                                if (firstFace != null)
                                {
                                    ++facesPresentCount;

                                    // Take the first face and the centre point of that face to try
                                    // and simplify things for my limited brain.
                                    var faceCentrePointInImageCoords =
                                        new Point(
                                            firstFace.FaceBox.X + (firstFace.FaceBox.Width / 2.0f),
                                            firstFace.FaceBox.Y + (firstFace.FaceBox.Height / 2.0f));

                                    wMatrix4x4 projectionTransform   = wMatrix4x4.Identity;
                                    wMatrix4x4 viewTransform         = wMatrix4x4.Identity;
                                    wMatrix4x4 invertedViewTransform = wMatrix4x4.Identity;

                                    var rgbCoordinateSystem = GetRgbFrameProjectionAndCoordinateSystemDetails(
                                        rgbFrame, out projectionTransform, out invertedViewTransform);

                                    // Scale the RGB point (1280x720)
                                    var faceCentrePointUnitScaleRGB = ScalePointMinusOneToOne(faceCentrePointInImageCoords, rgbFrame);

                                    // Unproject the RGB point back at unit depth as per the locatable camera
                                    // document.
                                    var unprojectedFaceCentrePointRGB = UnProjectVector(
                                        new wVector3(
                                            (float)faceCentrePointUnitScaleRGB.X,
                                            (float)faceCentrePointUnitScaleRGB.Y,
                                            1.0f),
                                        projectionTransform);

                                    // Transfrom this back by the inverted view matrix in order to put this into
                                    // the RGB camera coordinate system
                                    var faceCentrePointCameraCoordsRGB =
                                        wVector3.Transform(unprojectedFaceCentrePointRGB, invertedViewTransform);

                                    // Get the transform from the camera coordinate system to the Unity world
                                    // coordinate system, could probably cache this?
                                    var cameraRGBToWorldTransform =
                                        rgbCoordinateSystem.TryGetTransformTo(unityWorldCoordinateSystem);

                                    if (cameraRGBToWorldTransform.HasValue)
                                    {
                                        // Transform to world coordinates
                                        var faceCentrePointWorldCoords = wVector4.Transform(
                                            new wVector4(
                                                faceCentrePointCameraCoordsRGB.X,
                                                faceCentrePointCameraCoordsRGB.Y,
                                                faceCentrePointCameraCoordsRGB.Z, 1),
                                            cameraRGBToWorldTransform.Value);

                                        // Where's the camera in world coordinates?
                                        var cameraOriginWorldCoords = wVector4.Transform(
                                            new wVector4(0, 0, 0, 1),
                                            cameraRGBToWorldTransform.Value);

                                        // Multiply Z by -1 for Unity
                                        var cameraPoint = new uVector3(
                                            cameraOriginWorldCoords.X,
                                            cameraOriginWorldCoords.Y,
                                            -1.0f * cameraOriginWorldCoords.Z);

                                        // Multiply Z by -1 for Unity
                                        var facePoint = new uVector3(
                                            faceCentrePointWorldCoords.X,
                                            faceCentrePointWorldCoords.Y,
                                            -1.0f * faceCentrePointWorldCoords.Z);

                                        facePosition =
                                            cameraPoint +
                                            (facePoint - cameraPoint).normalized * centrePointDepthInMetres;
                                    }
                                }
                            }
                            if (facePosition != uVector3.zero)
                            {
                                UnityEngine.WSA.Application.InvokeOnAppThread(
                                    () =>
                                {
                                    this.faceMarker.transform.position = facePosition;
                                },
                                    false
                                    );
                            }
                        }
                    }
                    Interlocked.Exchange(ref busyProcessingRgbFrame, 0);
                }
                    );
            }
            else
            {
                Interlocked.Increment(ref rgbDroppedCount);
            }
            // NB: this is a bit naughty as I am accessing these counters across a few threads so
            // accuracy might suffer here.
            UnityEngine.WSA.Application.InvokeOnAppThread(
                () =>
            {
                this.textMesh.text =
                    $"{depthFrameCount} depth,{rgbProcessedCount} rgb done, {rgbDroppedCount} rgb drop," +
                    $"{facesPresentCount} faces, ({centrePointDepthInMetres:N2})";
            },
                false);
        };

        depthFrameReader.FrameArrived += depthFrameHandler;
        rgbFrameReader.FrameArrived   += rgbFrameHandler;

        await depthFrameReader.StartAsync();

        await rgbFrameReader.StartAsync();

        // Wait forever then dispose...just doing this to keep track of what needs disposing.
        await Task.Delay(-1);

        depthFrameReader.FrameArrived -= depthFrameHandler;
        rgbFrameReader.FrameArrived   -= rgbFrameHandler;

        rgbFrameReader.Dispose();
        depthFrameReader.Dispose();

        rgbMediaCapture.Item1.Dispose();
        depthMediaCapture.Item1.Dispose();

        Marshal.ReleaseComObject(unityWorldCoordinateSystem);
    }
Ejemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GuildOnlineMembersForm"/> class.
 /// </summary>
 /// <param name="guiManager">The GUI manager this <see cref="Control"/> will be managed by.</param>
 /// <param name="position">Position of the Control reletive to its parent.</param>
 /// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param>
 /// <exception cref="ArgumentNullException"><paramref name="guiManager"/> is null.</exception>
 public GuildOnlineMembersForm(IGUIManager guiManager, Vector2 position, Vector2 clientSize)
     : base(guiManager, position, clientSize)
 {
     _updateHandler = (x, y) => UpdateCache();
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GuildOnlineMembersForm"/> class.
 /// </summary>
 /// <param name="parent">Parent <see cref="Control"/> of this <see cref="Control"/>.</param>
 /// <param name="position">Position of the Control reletive to its parent.</param>
 /// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param>
 /// <exception cref="NullReferenceException"><paramref name="parent"/> is null.</exception>
 public GuildOnlineMembersForm(Control parent, Vector2 position, Vector2 clientSize) : base(parent, position, clientSize)
 {
     _updateHandler = (x, y) => UpdateCache();
 }
Ejemplo n.º 32
0
        private void Preview_ImageOpened(object sender, RoutedEventArgs e)
        {
            var viewModel = ViewModel;

            if (viewModel == null)
            {
                return;
            }

            var image = sender as GalleryContentView;

            if (image.Item != viewModel.FirstItem)
            {
                return;
            }

            var item = image.Item as GalleryContent;

            if (item == null)
            {
                return;
            }

            ScrollingHost.Opacity = 0;
            Preview.Opacity       = 1;

            var container = GetContainer(0);

            var animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("FullScreenPicture");

            if (animation != null)
            {
                if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimation", "Configuration"))
                {
                    animation.Configuration = new BasicConnectedAnimationConfiguration();
                }

                _layer.StartAnimation("Opacity", CreateScalarAnimation(0, 1));

                if (animation.TryStart(image.Presenter))
                {
                    TypedEventHandler <ConnectedAnimation, object> handler = null;
                    handler = (s, args) =>
                    {
                        animation.Completed -= handler;

                        Transport.Show();
                        ScrollingHost.Opacity = 1;
                        Preview.Opacity       = 0;

                        if (item.IsVideo && container != null)
                        {
                            Play(container.Presenter, item, item.GetFile());
                        }
                    };

                    animation.Completed += handler;

                    return;
                }
            }

            _layer.Opacity = 1;

            Transport.Show();
            ScrollingHost.Opacity = 1;
            Preview.Opacity       = 0;

            if (item.IsVideo && container != null)
            {
                Play(container.Presenter, item, item.GetFile());
            }
        }
 public void Dispose()
 {
     if (_popup != null)
         _popup.Closed -= PopupOnClosed;
     if (_weakSizeListener != null)
         Window.Current.SizeChanged -= _weakSizeListener;
     if (_weakInputPaneListener != null)
     {
         InputPane pane = InputPane.GetForCurrentView();
         if (pane != null)
         {
             pane.Hiding -= _weakInputPaneListener;
             pane.Showing -= _weakInputPaneListener;
         }
     }
     _popup = null;
     _weakSizeListener = null;
     _weakInputPaneListener = null;
     _settings = null;
 }
Ejemplo n.º 34
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;

            if (App.PreviousSubreddit == null || App.PreviousSubreddit != App.SelectedSubreddit || App.LastRefresh < DateTime.Now.Subtract(App.RefreshInterval))
            {
                App.JsonClient = new HttpClient();
                var response = App.JsonClient.GetAsync("http://www.reddit.com" + App.SelectedSubreddit.data.url + ".json").Result.Content;
                LoadCollection(response);
                App.LastRefresh = DateTime.Now;
            }
            else
            {
                Items = App.Posts.children;
                PageTitle.Text = App.SelectedSubreddit.data.url;
            }
            SetCurrentViewState(this);
        }
            public void Show()
            {
                Rect bounds = Window.Current.Bounds;
                var  child  = (FrameworkElement)_popupView;

                _popup = new Popup
                {
                    Width  = bounds.Width,
                    Height = bounds.Height,
                    Child  = child,
                    IsLightDismissEnabled = false,
                    ChildTransitions      =
                        new TransitionCollection
                    {
                        new PopupThemeTransition {
                            FromHorizontalOffset = 0, FromVerticalOffset = 100
                        }
                    }
                };
                InputPane inputPane = InputPane.GetForCurrentView();

                if (inputPane != null)
                {
                    _flyoutOffset = inputPane.OccludedRect.Height;
                }
                _settings = new PopupSettings
                {
                    UpdatePositionAction = UpdatePositionDelegate,
                    UpdateSizeAction     = UpdateSizeDelegate
                };
                _popupView.InitializePopup(_popup, _settings);
                UpdatePopup(bounds.Width, bounds.Height);
                _popup.Closed += PopupOnClosed;
                if (_settings.ShowAction == null)
                {
                    _popup.IsOpen = true;
                }
                else
                {
                    _settings.ShowAction(_popup);
                }
                _weakSizeListener = ReflectionExtensions
                                    .CreateWeakDelegate <PopupWrapper, WindowSizeChangedEventArgs, WindowSizeChangedEventHandler>(
                    this, (wrapper, o, arg3) => wrapper.OnWindowSizeChanged(arg3), (o, handler) => ((Window)o).SizeChanged -= handler, handler => handler.Handle);
                Window.Current.SizeChanged += _weakSizeListener;
                if (inputPane != null)
                {
                    _weakInputPaneListener = ReflectionExtensions
                                             .CreateWeakDelegate <PopupWrapper, InputPaneVisibilityEventArgs,
                                                                  TypedEventHandler <InputPane, InputPaneVisibilityEventArgs> >(this,
                                                                                                                                (wrapper, o, arg3) => wrapper.OnInputPaneChanged(arg3),
                                                                                                                                (o, handler) =>
                    {
                        var pane      = (InputPane)o;
                        pane.Hiding  -= handler;
                        pane.Showing -= handler;
                    }, handler => handler.Handle);
                    inputPane.Showing += _weakInputPaneListener;
                    inputPane.Hiding  += _weakInputPaneListener;
                }
            }
        /// <summary>
        /// Register for Added and Removed events.
        /// Note that, when disconnecting the device, the device may be closed by the system before the OnDeviceRemoved callback is invoked.
        /// </summary>
        private void RegisterForDeviceWatcherEvents()
        {
            deviceAddedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);

            deviceRemovedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);

            deviceWatcher.Added += deviceAddedEventHandler;

            deviceWatcher.Removed += deviceRemovedEventHandler;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WeakEventSubscription{T1, T2}" /> class.
 /// </summary>
 /// <param name="eventHandler">The event handler.</param>
 /// <param name="subscribeAction">The action to subscribe the event handler.</param>
 /// <param name="unsubscribeAction">The action to unsubscribe the event handler.</param>
 public WeakEventSubscription(TypedEventHandler <T1, T2> eventHandler, Action <TypedEventHandler <T1, T2> > subscribeAction, Action <TypedEventHandler <T1, T2> > unsubscribeAction)
     : this(eventHandler.Target, eventHandler, subscribeAction, unsubscribeAction)
 {
 }
        /// <summary>
        /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
        /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
        /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
        /// 
        /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
        /// </summary>
        private void RegisterForDeviceAccessStatusChange()
        {
            deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);

            deviceAccessEventHandler = new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
            deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Invoked when this page is about to be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached.  The Parameter
 /// property is typically used to configure the page.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     dataChangedHandler           = new TypedEventHandler <ApplicationData, object>(DataChangedHandler);
     applicationData.DataChanged += dataChangedHandler;
 }
 /// <summary>
 /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
 /// </summary>
 /// <param name="e">
 /// Event data that can be examined by overriding code. The event data is representative
 /// of the navigation that will unload the current Page unless canceled. The
 /// navigation can potentially be canceled by setting Cancel.
 /// </param>
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     base.OnNavigatingFrom(e);
     applicationData.DataChanged -= dataChangedHandler;
     dataChangedHandler = null;
 }
Ejemplo n.º 41
0
 public void RegisterSettingsRequestedHandler(TypedEventHandler <SettingsPane, SettingsPaneCommandsRequestedEventArgs> handler)
 {
     SettingsPane.GetForCurrentView().CommandsRequested += handler;
 }
Ejemplo n.º 42
0
        private async Task <WebTokenRequestResult> SignInAsync(string resource)
        {
            var taskCompletionSource = new TaskCompletionSource <WebTokenRequestResult>();

            TypedEventHandler <AccountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs> AccountCommandsRequestedHandler = null;

            AccountCommandsRequestedHandler = async(s, e) =>
            {
                Debug.WriteLine("AccountCommandsRequestedHandler");

                AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= AccountCommandsRequestedHandler;

                // In order to make async calls within this callback, the deferral object is needed
                AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
                if (deferral != null)
                {
                    // The Microsoft account provider is always present in Windows 10 devices, even IoT Core, as is the Azure AD plugin.
                    var providerCommand = new WebAccountProviderCommand(await GetProvider(), async(command) =>
                    {
                        Debug.WriteLine("WebAccountProviderCommandInvokedHandler");

                        try
                        {
                            WebTokenRequest wtr = new WebTokenRequest(command.WebAccountProvider, _scope, _clientId);
                            if (resource != null)
                            {
                                wtr.Properties.Add("resource", resource);
                            }

                            var wtrr = await RequestTokenWithTimeout(wtr);
                            SaveToken(wtrr, resource);

                            taskCompletionSource.SetResult(wtrr);
                        }
                        catch (Exception ex)
                        {
                            ServiceUtil.LogService.Write("Web Token Request Error: " + ex.Message, LoggingLevel.Error);
                            taskCompletionSource.SetResult(null);
                        }
                    });

                    e.WebAccountProviderCommands.Add(providerCommand);

                    deferral.Complete();
                }
            };

            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += AccountCommandsRequestedHandler;
            await AccountsSettingsPane.ShowAddAccountAsync();

            return(await taskCompletionSource.Task);
        }
Ejemplo n.º 43
0
        public void TestAvailableNoteRequest()
        {
            bool firstCheck = false;

            TypedEventHandler <IPenClient, object> availableNoteAccepted;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                firstCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote();
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            bool secondCheck = false;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                secondCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote(DEFAULT_SECTION, DEFAULT_OWNER, new int[] { DEFAULT_NOTE });
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            bool thirdCheck = false;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                thirdCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote(new int[] { DEFAULT_SECTION }, new int[] { DEFAULT_OWNER });
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            bool fourthCheck = false;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                fourthCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote(DEFAULT_SECTION, DEFAULT_OWNER);
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            bool fifthCheck = false;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                fifthCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote(DEFAULT_SECTION, DEFAULT_OWNER, null);
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            bool sixthCheck = false;

            availableNoteAccepted = new TypedEventHandler <IPenClient, object>((IPenClient sender, object args) =>
            {
                sixthCheck = true;
                _autoResetEvent.Set();
            });

            _controller.AvailableNoteAdded += availableNoteAccepted;

            Task.Factory.StartNew(() =>
            {
                _controller.AddAvailableNote(DEFAULT_SECTION, DEFAULT_OWNER, new int[] { 601, 602, 603, 604, 605, 606, 607, 608, 609, 610 });
            });

            _autoResetEvent.WaitOne();

            _controller.AvailableNoteAdded -= availableNoteAccepted;

            Assert.IsTrue(firstCheck && secondCheck && thirdCheck && fourthCheck && fifthCheck && sixthCheck);
        }
Ejemplo n.º 44
0
        public SensorTriggeredVideoCapture()
        {
            interruptEventHandler = null;

            this.InitializeComponent();
        }
Ejemplo n.º 45
0
 private void AttachEvent(TypedEventHandler <Accelerometer, AccelerometerReadingChangedEventArgs> ev)
 {
     _accelero.ReadingChanged += ev;
 }
Ejemplo n.º 46
0
        private void InitializeKeyEvent()
        {
            SyncPanel.Visibility     = Visibility.Collapsed;
            prologControl.Visibility = Visibility.Visible;
            mTargetVelocity          = mTargetSpeed;

            TypedEventHandler <CoreWindow, KeyEventArgs> mainPageKeyUpEvent = null;

            mainPageKeyUpEvent = async(sender, args) =>
            {
                Debug.WriteLine($"키보드 테스트: {args.VirtualKey}");

                if (prologControl.Visibility == Visibility.Visible)
                {
                    mTargetVelocity          = 0;
                    prologControl.Visibility = Visibility.Collapsed;

                    mainmenuPanel.Visibility = Visibility.Visible;
                }
                else
                {
                    if (args.VirtualKey == VirtualKey.Enter || args.VirtualKey == VirtualKey.GamepadA)
                    {
                        if (mFocusItem == 1)
                        {
                            Window.Current.CoreWindow.KeyUp -= mainPageKeyUpEvent;
                            Frame.Navigate(typeof(NewGamePage));
                        }
                        else if (mFocusItem == 2)
                        {
                            var saveFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync("loreSave.dat");

                            if (saveFile == null)
                            {
                                await new MessageDialog("저장된 게임이 없습니다. 새로운 게임을 시작해 주십시오.", "저장된 게임 없음").ShowAsync();
                            }
                            else
                            {
                                Window.Current.CoreWindow.KeyUp -= mainPageKeyUpEvent;
                                Frame.Navigate(typeof(GamePage));
                            }
                        }
                        else
                        {
                            await new MessageDialog("원작: 또다른 지식의 성전(안영기, 1993)\r\n\r\n" +
                                                    "음악: \r\n" +
                                                    "Town, Ground: https://www.zapsplat.com/\r\n" +
                                                    "Den: https://juhanijunkala.com/\r\n" +
                                                    "Keep: https://opengameart.org/content/boss-battle-theme", "저작권 정보").ShowAsync();
                        }
                    }
                    else if (mFocusItem == 1)
                    {
                        if (args.VirtualKey == VirtualKey.Down || args.VirtualKey == VirtualKey.GamepadDPadDown || args.VirtualKey == VirtualKey.GamepadLeftThumbstickDown)
                        {
                            newGameItem.Foreground  = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            loadGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 2;
                        }
                        else if (args.VirtualKey == VirtualKey.Up || args.VirtualKey == VirtualKey.GamepadDPadUp || args.VirtualKey == VirtualKey.GamepadLeftThumbstickUp)
                        {
                            newGameItem.Foreground  = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            exitGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 3;
                        }
                    }
                    else if (mFocusItem == 2)
                    {
                        if (args.VirtualKey == VirtualKey.Down || args.VirtualKey == VirtualKey.GamepadDPadDown || args.VirtualKey == VirtualKey.GamepadLeftThumbstickDown)
                        {
                            loadGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            exitGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 3;
                        }
                        else if (args.VirtualKey == VirtualKey.Up || args.VirtualKey == VirtualKey.GamepadDPadUp || args.VirtualKey == VirtualKey.GamepadLeftThumbstickUp)
                        {
                            loadGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            newGameItem.Foreground  = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 1;
                        }
                    }
                    else if (mFocusItem == 3)
                    {
                        if (args.VirtualKey == VirtualKey.Down || args.VirtualKey == VirtualKey.GamepadDPadDown || args.VirtualKey == VirtualKey.GamepadLeftThumbstickDown)
                        {
                            exitGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            newGameItem.Foreground  = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 1;
                        }
                        else if (args.VirtualKey == VirtualKey.Up || args.VirtualKey == VirtualKey.GamepadDPadUp || args.VirtualKey == VirtualKey.GamepadLeftThumbstickUp)
                        {
                            exitGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x53, 0x50, 0xf7));
                            loadGameItem.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff));
                            mFocusItem = 2;
                        }
                    }
                }
            };

            Window.Current.CoreWindow.KeyUp += mainPageKeyUpEvent;
        }
        void StartWatcher()
        {
            //deviceWatcher = DeviceInformation.CreateWatcher(UsbDevice.GetDeviceSelector(0x04d8, 0xf426));
            deviceWatcher = DeviceInformation.CreateWatcher(UsbDevice.GetDeviceSelector(TreehopperUsb.Settings.Vid, TreehopperUsb.Settings.Pid));
            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
            {
                Debug.WriteLine("Device added: " + deviceInfo.Name);

                UsbConnection newConnection = new UsbConnection(deviceInfo);

                TreehopperUsb newBoard = new TreehopperUsb(newConnection);
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    connectedDevices.Add(newBoard);
                });
                try
                {
                    if (boardAddedSignal.CurrentCount == 0)
                        boardAddedSignal.Release();
                }
                catch { }
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) =>
            {
                Debug.WriteLine("Device updated");
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
            {
                Debug.WriteLine("Device removed");
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    connectedDevices.Where(board => ((UsbConnection)(board.Connection)).DevicePath == deviceInfoUpdate.Id).ToList().All(i =>
                    {
                        i.Disconnect();
                        connectedDevices.Remove(i);
                        return true;
                    }
                    );
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler<DeviceWatcher, Object>((watcher, obj) =>
            {
                Debug.WriteLine("Enum completed");
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler<DeviceWatcher, Object>((watcher, obj) =>
            {
                Debug.WriteLine("Device or something stopped");
            });
            deviceWatcher.Stopped += handlerStopped;

            Debug.WriteLine("Starting the wutchah");
            deviceWatcher.Start();
        }
Ejemplo n.º 48
0
        private void StartWatcher()
        {
            startWatcherButton.IsEnabled = false;
            ResultCollection.Clear();

            // Get the device selector chosen by the UI then add additional constraints for devices that
            // can be paired or are already paired.
            DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
            //string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
            string selector = deviceSelectorInfo.Selector;

            if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
            {
                // Kind will be determined by the selector
                deviceWatcher = DeviceInformation.CreateWatcher(
                    selector,
                    null // don't request additional properties for this sample
                    );
            }
            else
            {
                // Kind is specified in the selector info
                deviceWatcher = DeviceInformation.CreateWatcher(
                    selector,
                    null, // don't request additional properties for this sample
                    deviceSelectorInfo.Kind);
            }

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);

                            // If the item being updated is currently "selected", then update the pairing buttons
                            DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
                            if (deviceInfoDisp == selectedDeviceInfoDisp)
                            {
                                UpdatePairingButtons();
                            }
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Watcher {1}.",
                                      ResultCollection.Count,
                                      DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
            deviceWatcher.Start();
            stopWatcherButton.IsEnabled = true;
        }
            public void Show()
            {
                Rect bounds = Window.Current.Bounds;
                var child = (FrameworkElement)_popupView;
                _popup = new Popup
                {
                    Width = bounds.Width,
                    Height = bounds.Height,
                    Child = child,
                    IsLightDismissEnabled = false,
                    ChildTransitions =
                        new TransitionCollection
                        {
                            new PopupThemeTransition {FromHorizontalOffset = 0, FromVerticalOffset = 100}
                        }
                };
                InputPane inputPane = InputPane.GetForCurrentView();
                if (inputPane != null)
                    _flyoutOffset = inputPane.OccludedRect.Height;
                _settings = new PopupSettings
                {
                    UpdatePositionAction = UpdatePositionDelegate,
                    UpdateSizeAction = UpdateSizeDelegate
                };
                _popupView.InitializePopup(_popup, _settings);
                UpdatePopup(bounds.Width, bounds.Height);
                _popup.Closed += PopupOnClosed;
                if (_settings.ShowAction == null)
                    _popup.IsOpen = true;
                else
                    _settings.ShowAction(_popup);
                _weakSizeListener = ReflectionExtensions
                    .CreateWeakDelegate<PopupWrapper, WindowSizeChangedEventArgs, WindowSizeChangedEventHandler>(
                        this, (wrapper, o, arg3) => wrapper.OnWindowSizeChanged(arg3), (o, handler) => ((Window)o).SizeChanged -= handler, handler => handler.Handle);
                Window.Current.SizeChanged += _weakSizeListener;
                if (inputPane != null)
                {
                    _weakInputPaneListener = ReflectionExtensions
                        .CreateWeakDelegate<PopupWrapper, InputPaneVisibilityEventArgs,
                            TypedEventHandler<InputPane, InputPaneVisibilityEventArgs>>(this,
                                (wrapper, o, arg3) => wrapper.OnInputPaneChanged(arg3),
                                (o, handler) =>
                                {
                                    var pane = (InputPane)o;
                                    pane.Hiding -= handler;
                                    pane.Showing -= handler;

                                }, handler => handler.Handle);
                    inputPane.Showing += _weakInputPaneListener;
                    inputPane.Hiding += _weakInputPaneListener;
                }
            }
Ejemplo n.º 50
0
        private void StartWatcher()
        {
            startWatcherButton.IsEnabled = false;
            ResultCollection.Clear();

            // First get the device selector chosen by the UI.
            DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;

            if (null == deviceSelectorInfo.Selector)
            {
                // If the a pre-canned device class selector was chosen, call the DeviceClass overload
                deviceWatcher = DeviceInformation.CreateWatcher(deviceSelectorInfo.DeviceClassSelector);
            }
            else if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
            {
                // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
                // Kind will be determined by the selector
                deviceWatcher = DeviceInformation.CreateWatcher(
                    deviceSelectorInfo.Selector,
                    null // don't request additional properties for this sample
                    );
            }
            else
            {
                // Kind is specified in the selector info
                deviceWatcher = DeviceInformation.CreateWatcher(
                    deviceSelectorInfo.Selector,
                    null, // don't request additional properties for this sample
                    deviceSelectorInfo.Kind);
            }

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Watcher {1}.",
                                      ResultCollection.Count,
                                      DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
            deviceWatcher.Start();
            stopWatcherButton.IsEnabled = true;
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Registers the event handler to be called again during the specified phase.
 /// </summary>
 /// <param name="e">The requested <see cref="CalendarViewDayItemChangingEventArgs"/>.</param>
 /// <param name="callbackPhase">The phase during which the callback should occur.</param>
 /// <param name="callback">The event handler function.</param>
 public static void RegisterUpdateCallbackWrapped(this CalendarViewDayItemChangingEventArgs e, uint callbackPhase, TypedEventHandler <CalendarView, CalendarViewDayItemChangingEventArgs> callback) => Resolver.RegisterUpdateCallback(e, callbackPhase, callback);
Ejemplo n.º 52
0
        /// <summary>
        /// Start the Device Watcher and set callbacks to handle devices appearing and disappearing
        /// </summary>
        private void StartWatcher()
        {
            //ProtocolSelectorInfo protocolSelectorInfo;
            string aqsFilter = @"System.Devices.Aep.ProtocolId:=""{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}"" OR System.Devices.Aep.ProtocolId:=""{bb7bb05e-5972-42b5-94fc-76eaa7084d49}""";  //Bluetooth + BluetoothLE

            // Request the IsPaired property so we can display the paired status in the UI
            string[] requestedProperties = { "System.Devices.Aep.IsPaired" };

            //// Get the device selector chosen by the UI, then 'AND' it with the 'CanPair' property
            //protocolSelectorInfo = (ProtocolSelectorInfo)selectorComboBox.SelectedItem;
            //aqsFilter = protocolSelectorInfo.Selector + " AND System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True";

            deviceWatcher = DeviceInformation.CreateWatcher(
                aqsFilter,
                requestedProperties,
                DeviceInformationKind.AssociationEndpoint
                );

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    bluetoothDeviceObservableCollection.Add(new BluetoothDeviceInformationDisplay(deviceInfo));
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (BluetoothDeviceInformationDisplay deviceInfoDisp in bluetoothDeviceObservableCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (BluetoothDeviceInformationDisplay deviceInfoDisp in bluetoothDeviceObservableCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            bluetoothDeviceObservableCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Finished enumerating
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await MainPage.Current.UIThreadDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Device watcher stopped
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            // Start the Device Watcher
            deviceWatcher.Start();
        }
        /// <summary>
        /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
        /// was ever connected.
        /// </summary>
        public void CloseDevice()
        {
            if (IsDeviceConnected)
            {
                CloseCurrentlyConnectedDevice();
            }

            if (deviceWatcher != null)
            {
                if (watcherStarted)
                {
                    StopDeviceWatcher();

                    UnregisterFromDeviceWatcherEvents();
                }

                deviceWatcher = null;
            }

            if (deviceAccessInformation != null)
            {
                UnregisterFromDeviceAccessStatusChange();

                deviceAccessInformation = null;
            }

            if (appSuspendEventHandler != null || appResumeEventHandler != null)
            {
                UnregisterFromAppEvents();
            }

            deviceInformation = null;
            deviceSelector = null;

            deviceConnectedCallback= null;
            deviceCloseCallback = null;

            isEnabledAutoReconnect = true;
        }
Ejemplo n.º 54
0
 void ICalendarViewDayItemChangingEventArgsResolver.RegisterUpdateCallback(CalendarViewDayItemChangingEventArgs e, uint callbackPhase, TypedEventHandler <CalendarView, CalendarViewDayItemChangingEventArgs> callback) => e.RegisterUpdateCallback(callbackPhase, callback);
        private void UnregisterFromDeviceWatcherEvents()
        {
            deviceWatcher.Added -= deviceAddedEventHandler;
            deviceAddedEventHandler = null;

            deviceWatcher.Removed -= deviceRemovedEventHandler;
            deviceRemovedEventHandler = null;
        }
Ejemplo n.º 56
0
 private void UnregisterFromDeviceAccessStatusChange()
 {
     DeviceAccessInformation.AccessChanged -= deviceAccessEventHandler;
     deviceAccessEventHandler = null;
 }
        private void UnregisterFromDeviceAccessStatusChange()
        {
            deviceAccessInformation.AccessChanged -= deviceAccessEventHandler;

            deviceAccessEventHandler = null;
        }
Ejemplo n.º 58
0
 public void Dispose()
 {
     _messageReceived = null;
     DisposeNative();
 }
 /// <summary>
 /// Invoked when this page is about to be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached.  The Parameter
 /// property is typically used to configure the page.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     dataChangedHandler = new TypedEventHandler<ApplicationData, object>(DataChangedHandler);
     applicationData.DataChanged += dataChangedHandler;
 }
        private void StartWatcher()
        {
            startWatcherButton.IsEnabled = false;
            ResultCollection.Clear();
            deviceWatchers.Clear();

            // Create all the event handlers

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));

                    UpdateStatusText();
                });
            });

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);
                            break;
                        }
                    }
                });
            });

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }

                    UpdateStatusText();
                });
            });

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    UpdateStatusText();
                });
            });

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    UpdateStatusText();
                });
            });

            // Create a watcher for each DeviceInformationKind selected by the user
            foreach (DeviceInformationKind deviceInfoKind in ((DeviceInformationKindChoice)kindComboBox.SelectedItem).DeviceInformationKinds)
            {
                DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(
                    "",     // AQS Filter string
                    null,   // requested properties
                    deviceInfoKind);

                deviceWatchers.Add(deviceWatcher);

                // Hook up handlers for the watcher events before starting the watcher

                deviceWatcher.Added   += handlerAdded;
                deviceWatcher.Updated += handlerUpdated;
                deviceWatcher.Removed += handlerRemoved;
                deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
                deviceWatcher.Stopped += handlerStopped;

                deviceWatcher.Start();
            }

            stopWatcherButton.IsEnabled = true;
            stopWatcherButton.Focus(FocusState.Keyboard);
        }