Recover the last stroke "InkCanvas" after closing the App

Javier R 211 Reputation points
2020-05-04T18:49:32.01+00:00

Recover the last stroke "InkCanvas" after closing the App and when opening the last stroke drawn the inkCanvas

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Daniele 1,996 Reputation points
    2020-05-04T20:02:49.077+00:00

    Given that the name of your InkCanvas is InkCanvas

    <InkCanvas  x:Name="InkCanvas" />
    

    To save at each stroke you can

    • use the StrokesCollected and StrokesErased events
    • use Application.Suspending event

    Using StrokesCollected and StrokesErased this can be your Page.Loaded event handler:

    private async void OnLoaded(object sender, RoutedEventArgs args)
    {
        InkCanvas.InkPresenter.StrokesCollected += async (presenter, eventArgs) => { await Save(); };
        InkCanvas.InkPresenter.StrokesErased += async (presenter, eventArgs) => { await Save(); };
        await Load();
    }
    

    Using Application.Suspending this can be your Page.Loaded event handler:

    private async void OnLoaded(object sender, RoutedEventArgs args)
    {
        Application.Current.Suspending += async (o, suspendingEventArgs) =>
        {
            SuspendingDeferral deferral = suspendingEventArgs.SuspendingOperation.GetDeferral();
            await Save();
            deferral.Complete();
        };
        await Load();
    }
    

    the Save and Load methods:

    private async Task Save()
    {
        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("strokes.ink",
                CreationCollisionOption.ReplaceExisting);
        using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            await InkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
            await stream.FlushAsync();
        }
    }
    
    private async Task Load()
    {
        IStorageItem storageItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync("strokes.ink");
        if (!(storageItem is StorageFile storageFile)) return;
        using (IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read))
        {
            await InkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
        }
    }
    

    I'm sure that file access in the Save method can be improved, anyway this works as a basic example.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Javier R 211 Reputation points
    2020-05-05T14:12:43.537+00:00

    the problem with putting the second line with += is that it produces an exception therefore I would have less.

    InkCanvas.InkPresenter.StrokesErased += async (presenter, eventArgs) .

    0 comments No comments