Showing posts with label wp7. Show all posts
Showing posts with label wp7. Show all posts

Thursday, March 20, 2014

How to take a screenshot from Windows Phone application code

  1. Catch camera button press by subscribing to CameraButtons.ShutterKeyReleased event.
  2. Get current page from Application.RootVisual property.
  3. Create an instance of WriteableBitmap class using this page.
  4. Save it to MemoryStream using WriteableBitmap.SaveJpeg extension method.
  5. Save image to JPEG file in public "Pictures/Saved Pictures" folder using MediaLibrary.SavePicture method.
Full code example below.

namespace Screenshot
{
    using System;
    using System.IO;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using Microsoft.Devices;
    using Microsoft.Phone.Controls;
    using Microsoft.Xna.Framework.Media;

    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            CameraButtons.ShutterKeyReleased += OnCameraButtonsShutterKeyReleased;
        }

        private void OnCameraButtonsShutterKeyReleased(Object sender, EventArgs e)
        {
            try
            {
                String fileName = "screenshot_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".jpg";

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(Application.Current.RootVisual, null);
                    writeableBitmap.SaveJpeg(memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);

                    memoryStream.Position = 0;

                    using (MediaLibrary mediaLibrary = new MediaLibrary())
                    {
                        mediaLibrary.SavePicture(fileName, memoryStream);
                    }
                }

                MessageBox.Show("Screenshot saved to " + fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error saving screenshot: " + ex.Message);
            }
        }
    }
}

Monday, May 6, 2013

Culture-specific sorting of CollectionViewSource using SortDescription

Just set Culture property of CollectionViewSource:

public CollectionViewSource All { get, private set; }
...
this.All = new CollectionViewSource();
this.All.Culture = new CultureInfo("fi-FI");
...
this.All.Source = this.items;
this.All.View.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

Friday, May 3, 2013

How to make text wrap in CheckBox control

It is very easy:
<CheckBox IsChecked="{Binding ShowPictures, Mode=TwoWay}">
    <TextBlock Text="Show pictures" TextWrapping="Wrap"/>
</CheckBox>

Wednesday, April 10, 2013

Answer: What is the size of "action icon" in PhoneTextBox control?

Image for "action icon" in PhoneTextBox control from Windows Phone toolkit should be 26 by 26 pixels.
<phone:PhoneApplicationPage
...
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit">
...
<toolkit:PhoneTextBox Hint="Search" ActionIcon="/Images/Search.png" />

Friday, March 15, 2013

Solution: Modify Pivot title in Windows Phone 7

To modify Pivot title in WP7, replace Title attribute with <Title> tag.

For example, to make Pivot control title red, change original XAML code

<Grid x:Name="LayoutRoot" Background="Transparent">

        <controls:Pivot Title="MY APPLICATION">
            
            <controls:PivotItem Header="Main">
            ...

to this:

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <controls:Pivot>

            <controls:Pivot.Title>
                <TextBlock Text="MY APPLICATION" Foreground="Red" />
            </controls:Pivot.Title>
            
            <controls:PivotItem Header="Main">
            ...

Wednesday, January 30, 2013

How to download WP7 Audio Recorder files to PC via USB cable

WP7 Audio Recorder is the best voice recorder for Windows Phone 7.

Unfortunately, upload to SkyDRive and Dropbox does not work, and that makes it almost not usable for me.

Fortunately, application developer implemented WP7 Isolated Storage Explorer (wp7explorer) support, so it is possible to download WAV files from WP7 phone to PC via USB cable.

Detailed instructions can be found on developers blog.

Tip: From my experience, downloading of big WAV files (more than 50 MB) can get stuck at the very end. In this case, just close the WP7 Isolated Storage Explorer after a minute or two.

Tuesday, February 21, 2012

[Solution] WP7: UnauthorizedAccessException with "Invalid cross-thread access" message

Symptoms

UnauthorizedAccessException exception with "Invalid cross-thread access" message is raised when accessing UI classes from OnInvoke method of a periodic task, e.g. when creating a live tile background image with WriteableBitmap.SaveJpeg.

Same exception is raised when accessing UI classes from a background thread (e.g. when using BackgroundWorker) or from any other async callback (e.g. WebRequest.BeginGetResponse).

Explanation

Any actions that will affect the UI must be executed from the UI thread.

Solution

Use Deployment.Current.Dispatcher.BeginInvoke method to execute your code on the UI thread.

public class ScheduledAgent : ScheduledTaskAgent
{
    ...
    
    protected override void OnInvoke(ScheduledTask task)
    {
        Deployment.Current.Dispatcher.BeginInvoke(UiThreadFunc);
    }

    private void UiThreadFunc()
    {
        Canvas canvas = new Canvas();

        ...

        WriteableBitmap writeableBitmap = new WriteableBitmap(173, 173);
        writeableBitmap.Render(canvas, null);
        writeableBitmap.Invalidate();

        using (IsolatedStorageFileStream isolatedStorageFileStream =
            IsolatedStorageFile.GetUserStoreForApplication().CreateFile("/Shared/ShellContent/TileBackground.jpg"))
        {
            writeableBitmap.SaveJpeg(isolatedStorageFileStream, 173, 173, 0, 100);
        }

        ...
    }
}

Monday, February 20, 2012

[Solution] "BNS error. The maximum number of SheduledActions of this type have already been added."

Symptoms

ScheduledActionService.Add() methods throws an InvalidOperationException exception with the following text: "BNS error. The maximum number of ScheduledActions of this type have already been added.".

Explanation

WP7 has a hardcoded limit of 1 (one) PeriodicTask per application.

So, if you already had added a PeriodicTask, you can't add more, and ScheduledActionService.Add() method throws an InvalidOperationException exception with the following text: "BNS error. The maximum number of SheduledActions of this type have already been added.".

It can happen for example when you change the name of your PeriodicTask (passed as a parameter in constructor).

Solution

Have exactly 1 (one) PeriodicTask per application.

Easiest way is to remove existing PeriodicTask before adding a new one:

    try
    {
        foreach (PeriodicTask oldTask in ScheduledActionService.GetActions<PeriodicTask>())
        {
            ScheduledActionService.Remove(oldTask.Name);
        }

        PeriodicTask newTask = new PeriodicTask("UpdateTile");
        newTask.Description = "Updates the tile on the start screen.";
        newTask.ExpirationTime = DateTime.Now.AddDays(14);

        ScheduledActionService.Add(newTask);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

Thursday, February 16, 2012

Silence incoming call on Windows Phone 7

Just press the power button.