Not able to call OnNavigatedFrom method after pressing lock key - c#

I am developing one app in windows phone. In my app it is necessary to handle lock key press event because I have used Timer. Here is my code
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
PhoneApplicationService.Current.Activated += Micropphone_Current_Activated;
PhoneApplicationService.Current.Deactivated += Micropphone_Current_Deactivated;
if (_autowizardtimer != null)
{
_autowizardtimer.Stop();
_autowizardtimer.Tick -= _timer_Tick;
if (_endtimer != null)
{
_endtimer.Stop();
_endtimer.Tick -= _endtimer_Tick;
}
}
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
if (_autowizardtimer != null)
{
PhoneApplicationService.Current.Activated -= Micropphone_Current_Activated;
PhoneApplicationService.Current.Deactivated -= Micropphone_Current_Deactivated;
_autowizardtimer.Stop();
_autowizardtimer.Tick -= _timer_Tick;
}
if (_endtimer != null)
{
_endtimer.Stop();
_endtimer.Tick -= _endtimer_Tick;
}
}
Basically what I am trying to do is, when user press lock key the timer get's pause and after releasing lock key timer get's start. The problem is in OnNavigatedFrom method. When I press lock key this method is not calling. I am not getting what is the problem. Can some please tell why this is happening? Or Is there any other way to handle lock key press ?

You don't need to stop the timer when the screen is locked, because your application will automatically be deactivated (unless you've explicitly told the system that you want your application to run under the lock screen).
Still, if you want to detect the moment when the screen is locked or unlocked, you can use the events Obscured and Unobscured respectively.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206951(v=vs.105).aspx#BKMK_Understandingtheeventsthatoccurwhenthephoneislockedorunlocked

When you press the lock key you basically don't navigate from the page, but you're deactivating your app. In your case I would handle this timer in the App.xaml.cs Activated and Deactivated events also.
Please take a look at the Windows Phone Application Lifecycle here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff817008(v=vs.105).aspx
Regards,

Related

GlobalSystemMediaTransportControlsSession event problems

I've implemented this class of Microsoft.Windows.SDK.Contracts nuget package for monitoring the actions (play and pause) of a third party music player.
Everything works except that after some time the events are no longer triggered.
This is the code:
public void startMediaListener()
{
GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult().CurrentSessionChanged += callbackSessionChanged;
GlobalSystemMediaTransportControlsSession currentSession = GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult().GetCurrentSession();
if (currentSession == null || !currentSession.SourceAppUserModelId.ToLower().Contains("appNameToMonitor"))
return;
Console.WriteLine("Started");
currentSession.PlaybackInfoChanged += callbackPlaybackStatus;
currentHashSession = currentSession.GetHashCode();
serviceRunning = true;
}
Event when session changed
private void callbackSessionChanged(GlobalSystemMediaTransportControlsSessionManager session, CurrentSessionChangedEventArgs e)
{
Console.WriteLine("Session changed" + session.GetCurrentSession().GetHashCode().ToString());
if (session.GetCurrentSession() == null || !session.GetCurrentSession().SourceAppUserModelId.ToLower().Contains("appNameToMonitor"))
return;
session.GetCurrentSession().PlaybackInfoChanged += callbackPlaybackStatus;
currentHashSession = session.GetCurrentSession().GetHashCode();
}
Event for detecting pause/play
private void callbackPlaybackStatus(GlobalSystemMediaTransportControlsSession session, PlaybackInfoChangedEventArgs e)
{
if (!session.SourceAppUserModelId.ToLower().Contains("spotify") || currentHashSession != session.GetHashCode())
return;
GlobalSystemMediaTransportControlsSessionPlaybackStatus status = session.GetPlaybackInfo().PlaybackStatus;
double currentTime = session.GetTimelineProperties().LastUpdatedTime.TimeOfDay.TotalMilliseconds;
//Do work...
}
I also check the hashcode because if I listen to Spotify then youtube then Spotify again the 2 sessions of Spotify have different hashcode and it will trigger the event twice (when it works) and I want to monitor only the last one.
The problem is that in startMediaListener() I can find the session of my app and everything works for few minutes but after some time the callbackPlaybackStatus is no longer called and meanwhile no session changed so I suppose that the session is still up but not firing the event.
Can you help me solve this mistery?
Ps: I've tried to put everything inside a thread but this solution doesn't works.

how to know when a device unlocks using the LockApplicationHost class in winRT apps

here's what I've done in my universal windows app:
public MainPage()
{
InitializeComponent();
private LockApplicationHost lol=LockApplicationHost.GetForCurrentView();
}
private async void Lol_Unlocking(LockApplicationHost sender, LockScreenUnlockingEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
alarm.Pause();
Status.Text = "lolwtf";
});
}
I'm trying to know when the user unlocks his computer.
EDIT: also the error I keep getting is:
Delegate to an instance method cannot have null 'this'. and it highlights:
lol.Unlocking += Lol_Unlocking;
I'm trying to know when the user unlocks his computer.
You can hookup a SessionSwitchEventHandler. Obviously your application will need to be running. SessionSwitchEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event.
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
You can have a look on the SessionSwitchReason Enumeration to find more about the uses the SessionSwitchReason class to represent the type of a session switch event.
lol.Unlocking += Lol_Unlocking;
should be lol.Unlocking += Lol_Unlocking(EventHandler_Unlocking); and EventHandler_Unlocking has to be defined in the program.
my understanding for LockApplicationHost.Unlocking is that it helps to unlock and lock the device whereas to determine if the device is unlocked and unlocked SessionSwitchEventHandler will be better approach. For more understanding on the LockApplicationHost.Unlocking check this

Suppressing global windows shortcuts while recording keypresses

Is it possible to suppress the windows global shortcuts while recording keypresses ?
I have a Windows Form application written in c#, and using this library to record keypresses to use later in macros. Now when I record the key combinations that are used by Windows (i.e. L Control + Win + Right Arrow to change virtual desktop on Win 10), I'd like my app to record it but avoid windows actually using it while I record which is quite annoying.
I have a checkbox to enable key capturing, on click event
m_KeyboardHookManager.KeyDown += HookManager_KeyDown;
the HookManager_KeyDown is simply like this
private void HookManager_KeyDown(object sender, KeyEventArgs e)
{
Log(string.Format("KeyDown \t\t {0}\n", e.KeyCode));
string [] sArr = new string [2];
if (keyBindingArea1.Text != "")
{
sArr[0] = keyBindingArea1.Text;
sArr[1] = string.Format("{0}", e.KeyCode);
keyBindingArea1.Text = string.Join("+", sArr);
}
else
{
keyBindingArea1.Text = string.Format("{0}", e.KeyCode);
}
}
which display the key combination in a comboText control. (This code is taken directly from the demo attached to the package.
Now the recording work well if for instance I press L Control + Win, then I release the keys and press the third one (i.e. Right Arrow), this will not trigger Windows shortcuts but it is quite annoying to have it work like that.
Appreciate any help. Thanks
Try to use e.Handled property of the event. If you set it to true it will terminate key procesing chain. As a rule oher applications in the processing chain will not get it. I am not sure it is going to work for such a low level windows staff as virtual desktop switch.
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
bool isThirdKey = //Some state evaluation to detect the third key was pressed
if (isThirdKey) e.Handled = true;
}

Pressing a key will spawn a lot of screens

I have the code below:
else if (keyboardState.IsKeyDown(Keys.E)) // if the 'E' key is pressed
{
form = new InventoryScreen(); //define winform instance
form.Show(); //display winform
}
It works, maybe too well. Because when the user presses and holds the 'E' key, the program generates a lot of winform screens. Is there a way to instruct the program to only run the following only once? Also, how would I write it so that if I press the 'E' key again, the window will disapear?
I would create a separate event handler firing on keyup. Within the handler you can check to see if the key is indeed 'E'. The keyup event will only fire once when the key is pressed and not fire while the key is held down.
See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx
XNA is not event-driven, it is instead a game loop.
There is no built-in event that fires on keys being press or not. One option is to only handle the 'E' event if no form is created.
A second option is to keep the old keyboard state, like this:
KeyboardState oldState;
Update(..):
KeyboardState now = Keyboard.GetState();
if (now.IsKeyUp(Keys.E) && oldState.IsKeyDown(Keys.E))
// i.e. a "release event"
{
form.Show();
}
oldState = now;
For the variant with disappearing, this might work or something similar, but you should probably instead handle it in the created form:
KeyboardState now = Keyboard.GetState();
if (now.IsKeyUp(Keys.E) && oldState.IsKeyDown(Keys.E))
// i.e. a "release event"
{
if (form.Visible)
{
form.Hide();
}
else
{
form.Show();
}
}
oldState = now;

Maximize C# Application from System Tray using Keyboard Shortcut

Can I know if there is anyway that I can maximise my windows form application from the system tray using say a Keyboard Shortcut rather than clicking on it?
I am currently minimizing using this piece of code
//Minimize to Tray with over-ride for short cut
private void MinimiseToTray(bool shortCutPressed)
{
notifyIcon.BalloonTipTitle = "Minimize to Tray App";
notifyIcon.BalloonTipText = "You have successfully minimized your app.";
if (FormWindowState.Minimized == this.WindowState || shortCutPressed)
{
notifyIcon.Visible = true;
notifyIcon.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon.Visible = false;
}
}
Hence, I need a keyboard shortcut that should maximize it. Much thanks!
EDIT: If you simply want to 'reserve a key combination' to perform something on your application, a Low-Level keyboard hook whereby you see every keypress going to any other application is not only an overkill, but bad practice and in my personal view likely to have people thinking that you're keylogging! Stick to a HOT-KEY!
Given that your icon will not have keyboard focus, you need to register a global keyboard hotkey.
Other similar questions:
How can I register a global hot key to say CTRL+SHIFT+(LETTER)
Best way to tackle global hotkey processing in c#?
Example from Global Hotkeys With .NET:
Hotkey hk = new Hotkey();
hk.KeyCode = Keys.1;
hk.Windows = true;
hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };
if (!hk.GetCanRegister(myForm))
{
Console.WriteLine("Whoops, looks like attempts to register will fail " +
"or throw an exception, show error to user");
}
else
{
hk.Register(myForm);
}
// .. later, at some point
if (hk.Registered)
{
hk.Unregister();
}
To do this, you must use "Low-Level Hook".
You will find all information about it on this article : http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx
Look at this too : http://www.codeproject.com/Articles/6362/Global-System-Hooks-in-NET
I second Franck's suggestion about a global keyboard hook. Personally, I had very good experiences with the CodeProject article "Processing Global Mouse and Keyboard Hooks in C#".
As they write in their article, you can do things like:
private UserActivityHook _actHook;
private void MainFormLoad(object sender, System.EventArgs e)
{
_actHook = new UserActivityHook();
_actHook.KeyPress += new KeyPressEventHandler(MyKeyPress);
}
You could then call a function in your MyKeyPress handler that opens your window.
If you follow the guide here. It will show you how to register a global shortcut key.
public partial class Form1 : Form
{
KeyboardHook hook = new KeyboardHook();
public Form1()
{
InitializeComponent();
// register the event that is fired after the key press.
hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
// register the CONTROL + ALT + F12 combination as hot key.
// You can change this.
hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12);
}
private void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
// Trigger your function
MinimiseToTray(true);
}
private void MinimiseToTray(bool shortCutPressed)
{
// ... Your code
}
}

Categories