Fast App Resume not working - c#

I am trying to implement Fast app resume for Windows Phone 8. I followed the link at MSDN.
And here is the code in XAML:
<Tasks>
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" ActivationPolicy="Resume"/>
</Tasks>
And this is the code in app.xaml.cs
public static PhoneApplicationFrame RootFrame { get; private set; }
bool wasRelaunched = false;
bool mustClearPagestack = false;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
enum SessionType
{
None,
Home,
DeepLink
}
private SessionType sessionType = SessionType.None;
public App()
{
UnhandledException += Application_UnhandledException;
InitializeComponent();
InitializePhoneApplication();
InitializeLanguage();
if (Debugger.IsAttached)
{
Application.Current.Host.Settings.EnableFrameRateCounter =true;
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
private void Application_Launching(object sender, LaunchingEventArgs e)
{
RemoveCurrentDeactivationSettings();
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
mustClearPagestack = CheckDeactivationTimeStamp();
if (!e.IsApplicationInstancePreserved)
{
RestoreSessionType();
}
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
SaveCurrentDeactivationSettings();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
RemoveCurrentDeactivationSettings();
}
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
private void Application_UnhandledException(object sender,ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
private bool phoneApplicationInitialized = false;
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
RootFrame= new PhoneApplicationFrame();
RootFrame.Background = new SolidColorBrush(Color.FromArgb(255, 27, 200, 174));
RootFrame.Navigated += CompleteInitializePhoneApplication;
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
RootFrame.Navigated += CheckForResetNavigation;
RootFrame.Navigating += RootFrame_Navigating;
phoneApplicationInitialized = true;
}
void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
if (e.Uri.ToString().Contains(#"/MainPage.xaml") == true && !AppPrefManager.Instance.IsFastAppResumeEnabled)
{
RootFrame.Dispatcher.BeginInvoke(delegate
{
if (!AppPrefManager.Instance.IsVirginLaunchCompleted)
{
RootFrame.Navigate(new Uri(Constants.kIntroPage, UriKind.Relative));
}
else
{
RootFrame.Navigate(new Uri(Constants.kMainPage, UriKind.Relative));
}
});
e.Cancel = true;
}
if (sessionType == SessionType.None && e.NavigationMode == NavigationMode.New)
{
if (e.Uri.ToString().Contains("DeepLink=true"))
{
sessionType = SessionType.DeepLink;
}
else if (e.Uri.ToString().Contains("/MainPage.xaml"))
{
sessionType = SessionType.Home;
}
}
if (e.NavigationMode == NavigationMode.Reset)
{
wasRelaunched = true;
}
else if (e.NavigationMode == NavigationMode.New && wasRelaunched)
{
wasRelaunched = false;
if (e.Uri.ToString().Contains("DeepLink=true"))
{
sessionType = SessionType.DeepLink;
}
else if (e.Uri.ToString().Contains("/MainPage.xaml"))
{
if (sessionType == SessionType.DeepLink)
{
sessionType = SessionType.Home;
}
else
{
if (!mustClearPagestack)
{
e.Cancel = true;
RootFrame.Navigated -= ClearBackStackAfterReset;
}
}
}
mustClearPagestack = false;
}
}
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
if (RootVisual != RootFrame)
RootVisual = RootFrame;
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
RootFrame.Navigated -= ClearBackStackAfterReset;
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
while (RootFrame.RemoveBackEntry() != null)
{
;
}
}
private void InitializeLanguage()
{
try
{
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
bool CheckDeactivationTimeStamp()
{
DateTimeOffset lastDeactivated;
if (settings.Contains("DeactivateTime"))
{
lastDeactivated = (DateTimeOffset)settings["DeactivateTime"];
}
var currentDuration = DateTimeOffset.Now.Subtract(lastDeactivated);
return TimeSpan.FromSeconds(currentDuration.TotalSeconds) > TimeSpan.FromSeconds(30);
}
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
if (settings.Contains(Key))
{
if (settings[Key] != value)
{
settings[Key] = value;
valueChanged = true;
}
}
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public void RemoveValue(string Key)
{
if (settings.Contains(Key))
{
settings.Remove(Key);
}
}
public void SaveCurrentDeactivationSettings()
{
if (AddOrUpdateValue("DeactivateTime", DateTimeOffset.Now))
{
settings.Save();
}
if (AddOrUpdateValue("SessionType", sessionType))
{
settings.Save();
}
}
public void RemoveCurrentDeactivationSettings()
{
RemoveValue("DeactivateTime");
RemoveValue("SessionType");
settings.Save();
}
void RestoreSessionType()
{
if (settings.Contains("SessionType"))
{
sessionType = (SessionType)settings["SessionType"];
}
}
Suppose while I am in ThirdPage. I press the Windows button. And then I press my App icon from the start screen. Rather than the app resuming from the ThirdPage. It first shows the ThirdPage and then starts from the MainPage.

By default, the app still navigates to the default page, when the application is launched via the app tile.
You can check the session type in the RootFrame_Navigated methods and cancel that navigation, if you so wish.
The default template adds a CheckNavigation method to in the app.xaml.cs that clears the backstack after a navigation with NavigationMode Reset.
You can check there, if your app should stay on the last page or if it is better to reset and start over.
A sample for handling different activation types can be found here:
MSDN Fast Resume Sample, App.xaml.cs
(Method: RootFrame_Navigated)

Code as listed will mess up. It doesn't match the comments.
Look at the RootFrame_Navigating - mustClearPagesStack at the bottom is set to false - but look at the comments in the original MSDN link - two places above it say the page stack must be cleared.... but because the flag is set to false it's messed up. So set the flag false at the top, but then set it to true in the two 'if conditions' where it says to.
Then it will work like a champ.

Related

Sending cancel parameter C#

Okay, this is my whole code. Now... Detail_BeforePrint() will be called first, and xrPictureBox8_BeforePrint second.
Now I want to call Detail_BeforePrint e.Cancel = true; inside the else in xrPictureBox8_BeforePrint event.
private void Detail_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
//here should e.Cancel = true be if it came from xrPictureBox_BeforePrint()
}
private void xrPictureBox8_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
if (xrPictureBox8.ImageUrl.Length > 0) { }
else
{
Detail_BeforePrint(null,[call Cancel parameter]);
}
}
catch (Exception)
{
}
}
Maybe something like this would help?
private void Detail_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
DoDetail_BeforePrint(e, false);
}
private void DoDetail_BeforePrint(System.Drawing.Printing.PrintEventArgs e, bool cancel)
{
if (cancel) e.Cancel = true;
//other things
}
private void xrPictureBox8_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
if (xrPictureBox8.ImageUrl.Length > 0) { }
else
{
DoDetail_BeforePrint(e, true);
//or just call e.Cancel = true here?
}
}
catch (Exception)
{
}
}

How to solve memory leak in window form

My problem is that memory is increased 5MB flicker form each time a call per second .
I made window flicker effect window form
[flicker form]
public partial class WarningBoxControls : Form
{
bool _isShadow;
public WarningBoxControls(WarningBoxType _Type)
{
InitializeComponent();
this.FormClosing += WarningBox_FormClosing;
this.VisibleChanged +=WarningBoxControls_VisibleChanged;
if (_Type == WarningBoxType.WarningBox_Speed)
{
MessageTitle.Text = "속력 경고";
MessageContent.Text = "자동차 속도를 줄여주세요!";
this.BackColor = Color.SkyBlue;
pictureBox1.Image = Properties.Resources.warning_speed;
}
else
{
MessageTitle.Text = "Logger 오류";
MessageContent.Text = "Logger가 활성화되지 않았습니다!";
this.BackColor = Color.MediumVioletRed;
pictureBox1.Image = Properties.Resources.warning_error;
}
}
private void WarningBoxControls_VisibleChanged(object sender, EventArgs e)
{
this.Opacity = 0.01;
if(this.Visible == true)
{
timer1.Start();
}
else
{
timer1.Stop();
}
}
private void WarningBox_FormClosing(object sender, FormClosingEventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image = null;
pictureBox1.Dispose();
}
if (timer1.Enabled == true)
{
timer1.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_isShadow == false)
{
if (this.Opacity <= 1.0)
{
this.Opacity += 0.8;
if (this.Opacity >= 1.0)
{
_isShadow = true;
}
}
}
else
{
if (this.Opacity >= 0.01)
{
this.Opacity -= 0.08;
if (this.Opacity <= 0.01)
{
_isShadow = false;
}
}
}
}
}
And I created the class to load flicker effect form.
[load ficker form]
public class WarningBox
{
WarningBoxControls _control;
Form owner;
public WarningBox(IWin32Window _owner, WarningBoxType _Type)
{
if (_owner != null)
{
owner = (Form)_owner;
_control = new WarningBoxControls(_Type);
_control.StartPosition = FormStartPosition.Manual;
_control.Padding = new Padding(0, 0, 0, 0);
_control.ControlBox = false;
_control.ShowInTaskbar = false;
_control.Size = new Size(owner.Size.Width - 40, _control.Height - 20);
}
}
public void Show()
{
_control.Location = new Point(owner.Location.X + 20, owner.Location.Y + ((owner.Height - _control.Height) / 2));
//_control.ShowDialog();
//_control.BringToFront();
if(_control.Visible != true)
{
_control.Show();
_control.BringToFront();
}
}
public void Hide()
{
if(_control.Visible != false)
{
//_control.Visible = false;
_control.Hide();
}
}
~WarningBox()
{
if(_control != null)
{
_control.Dispose();
_control = null;
}
}
}
[Call a second method]
private void timer1_Tick(object sender, EventArgs e)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
ReadLoggerStatus();
}
private void ReadLoggerStatus()
{
if (_Lights != null)
{
if (_Lights.ERR == 0) // 에러 없을때
{
pb_error.Image = Properties.Resources.none;
_WarningBox.Hide();
btn_stop.Enabled = true;
btn_start.Enabled = false;
}
else
{
pb_error.Image = Properties.Resources.error;
_WarningBox.Show();
btn_stop.Enabled = false;
btn_start.Enabled = true;
}
}
}
And Check the one error per second , call the Show() and Hide() of WarningBox. however here(ReadLoggerStatus()) is some of a problem.
my problem is that the memory each time it is called once per second increased by 5MB.
I want to know it is solve the best way.
please let me know excellent answer.
In advance, I would greetings of thanks.
Have a good day!

Reorder StackPanel Children Drag & Drop

I got a Stackpanel containing many buttons, so how can I reorder my buttons by draging & droping them like Expression Blend or "Visual Studio Xaml Window Designer" does
This thread provides some useful information. Nevertheless, there are a lot of resources that you can find in by searching which would provide a lot of information on this.
I am developing an arrangeable stack panel, when I touch or press the item and release the mouse and move the object or child in the stack panel is stick with it. my Code is as below.
namespace Controls.ArrangableGrid
{
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Documents;
public class ArrangableControl : StackPanel
{
#region - Variables -
private bool _isDown;
private bool _isDragging;
private Point _startPoint;
private DragAdorner _adorner;
private UIElement _draggedItem = null;
private int _draggedItemIndex = -1;
private ILoggingService _logging = null;
private ILogger _logger;
private CypherComponentModel _parentComponent = null;
#endregion
public ArrangableControl()
{
Orientation = Orientation.Horizontal;
Background = Brushes.Transparent;
if (!DesignerProperties.GetIsInDesignMode(this))
{
Loaded += OnLoaded;
}
}
#region - Functions -
private void SetEvetns()
{
AllowDrop = true;
Drop += OnDrop;
StylusDown += OnEventDown;
StylusUp += OnEventUp;
StylusMove += OnEventMove;
MouseLeftButtonDown += OnEventDown;
MouseLeftButtonUp += OnEventUp;
MouseMove += OnEventMove;
}
private Point GetPosition(InputEventArgs e, IInputElement obj)
{
if (e is MouseEventArgs)
{
Mouse.Capture(obj);
return (e as MouseEventArgs).GetPosition(obj);
}
else if (e is TouchEventArgs)
{
(e as TouchEventArgs).TouchDevice.Capture(obj);
return (e as TouchEventArgs).GetTouchPoint(obj).Position;
}
else if (e is StylusEventArgs)
{
Stylus.Capture(obj);
return (e as StylusEventArgs).GetPosition(obj);
}
return new Point();
}
private void DragStarted()
{
if (_draggedItem == null) return;
_isDragging = true;
_adorner = new DragAdorner(_draggedItem);
var layer = AdornerLayer.GetAdornerLayer(_draggedItem);
layer.Add(_adorner);
}
private void DragMoved()
{
var currentPosition = Mouse.GetPosition(this);
_adorner.LeftOffset = currentPosition.X - _startPoint.X;
_adorner.TopOffset = currentPosition.Y - _startPoint.Y;
}
private void DragFinished(bool cancelled, InputEventArgs e)
{
this.ReleaseMouseCapture();
if (null != _adorner)
AdornerLayer.GetAdornerLayer(_adorner.AdornedElement).Remove(_adorner);
if (cancelled == false)
{
UIElement _dropItem = this.GetChildElement(GetPosition(e, this)) as UIElement;
if (null != _dropItem)
DragDrop.DoDragDrop(_draggedItem, new DataObject("UIElement", e.Source, true), DragDropEffects.Move);
}
_adorner = null;
_isDragging = false;
_isDown = false;
}
#endregion
#region - Events -
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (this.IsLoaded)
{
SetEvetns();
}
}
private void OnEventDown(object sender, InputEventArgs e)
{
if(e.Source != this)
{
_isDown = true;
_isDragging = false;
_startPoint = GetPosition(e, this);
_draggedItem = e.Source as UIElement;
if (null != _draggedItem)
_draggedItemIndex = this.Children.IndexOf(_draggedItem);
}
}
private void OnEventUp(object sender, InputEventArgs e)
{
if (_isDown && _isDragging)
{
DragFinished(false, e);
e.Handled = true;
}
else
{
e.Handled = true;
ReleaseMouseCapture();
ReleaseAllTouchCaptures();
ReleaseStylusCapture();
}
}
private void OnEventMove(object sender, InputEventArgs e)
{
if (_isDown)
{
if ((_isDragging == false) &&
((Math.Abs(GetPosition(e, this).X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance) ||
(Math.Abs(GetPosition(e, this).Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)))
DragStarted();
if (_isDragging)
DragMoved();
}
e.Handled = true;
}
private void OnDrop(object sender, DragEventArgs e)
{
try
{
UIElement droptarget = e.Source as UIElement;
int droptargetIndex = this.Children.IndexOf(droptarget);
if (_draggedItem != null && (droptargetIndex != _draggedItemIndex))
{
if (droptargetIndex != -1)
{
this.Children.Remove(_draggedItem);
this.Children.Insert(droptargetIndex, _draggedItem);
}
}
_draggedItem = null;
_draggedItemIndex = -1;
}
catch (Exception ex)
{
_logger.Error($"Drop Error: {ex} at {nameof(ArrangableControl)}");
}
finally
{
e.Handled = true;
ReleaseMouseCapture();
ReleaseAllTouchCaptures();
ReleaseStylusCapture();
}
}
#endregion
}
}

Movable UserControl in WPF

I created simple UserControl with several labels. How can I implement simple mechanism, that allows moving whole control like normal window (when I add it to winForms - if it makes difference)
You can use my Capture class:
public class ClsCapture
{
bool bCaptureMe;
Point pLocation = new Point();
Control dd;
//Handles dad.MouseDown, dd.MouseDown
private void Form1_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try {
bCaptureMe = true;
pLocation = e.GetPosition(sender);
} catch {
}
}
//Handles dad.MouseMove, dd.MouseMove
private void Form1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
try {
if (bCaptureMe) {
dd.Margin = new Thickness(dd.Margin.Left - pLocation.X + e.GetPosition(sender).X, dd.Margin.Top - pLocation.Y + e.GetPosition(sender).Y, dd.Margin.Right, dd.Margin.Bottom);
}
} catch {
}
}
//Handles dad.MouseUp, dd.MouseUp
private void Form1_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try {
bCaptureMe = false;
} catch {
}
}
public ClsCapture(Control pnl)
{
dd = pnl;
dd.PreviewMouseLeftButtonDown += Form1_MouseDown;
dd.PreviewMouseLeftButtonUp += Form1_MouseUp;
dd.PreviewMouseMove += Form1_MouseMove;
}
public static void CaptureMe(Control pnl)
{
ClsCapture cc = new ClsCapture(pnl);
}
}
Usage:
ClsCapture.CaptureMe(AnyControlYouWant);

Is there any way to replay a video in Windows Media Control?

How I can replay a video in Windows Media control? I try to do it by this way? but it doesn't work
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
//mediaPlayer.currentPlaylist = mediaPlayer.mediaCollection.getByName("Dastan");
//mediaPlayer.URL = #"C:\Documents and Settings\Администратор\Мои документы\Моя музыка\Мои списки воспроизведения\Dastan.wpl";
//mediaPlayer.uiMode = "none";
PlayFile(#"C:\Documents and Settings\Администратор\Мои документы\Моя музыка\Мои списки воспроизведения\Dastan.wpl");
}
private void mediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPPlayState.wmppsPlaying)
{
mediaPlayer.fullScreen = true;
mediaPlayer.Ctlenabled = false;
}
else if ((WMPLib.WMPPlayState)e.newState == WMPPlayState.wmppsMediaEnded)
{
Form1_Load(null, null);
}
}
private void PlayFile(String url)
{
mediaPlayer.URL = url;
mediaPlayer.Ctlcontrols.play();
}
Any ideas?
mediaPlayer.settings.setMode("loop", true);
This code snippet does all job. Thanks for answers..
Try setting mediaPlayer.Ctlcontrols.currentPosition to 0.
private void mediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPPlayState.wmppsPlaying)
{
mediaPlayer.fullScreen = true;
mediaPlayer.Ctlenabled = false;
}
else if ((WMPLib.WMPPlayState)e.newState == WMPPlayState.wmppsMediaEnded)
{
mediaPlayer.Ctlcontrols.currentPosition = 0;
mediaPlayer.Ctlcontrols.play();
}
}

Categories