detecting if shift was held when application started - wpf

Is there anyway that I can find out if user has been holding Shift (CTRL or any other key) when she/he double click on application icon from desktop to start the application?
I have a WPF application where I want to be able to detect if the user has been holding any special key when he/she started the application (by double clicking) so I can change some settings if the key was pressed.
I tried :
private void Application_Startup(object sender, StartupEventArgs e)
{
}
but couldn't find any way to detect the key down .

Write this code in your application start-up event:
// Instead of the MessageBox you could write your code here
if ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)
{
MessageBox.Show("Shift Pressed");
}

I think you should look at this question: Keyboard modifiers during application startup This is probably what you're looking for.
Hope it helps.

Related

Use custom on-screen keyboard form with OpenFileDialog and SaveFileDialog

We have a custom on-screen keyboard (OSK) form as part of our .NET Windows Forms Application. This keyboard is useful to enter data into a DataGridView and some other textboxes. We want to be able to use it to enter a file name into an OpenFileDialog or SaveFileDialog.
However, when either Dialog shows up, the form containing the OSK stops responding to input. I tried creating a new Form that is used as the OSK's owner. I use the new form and call keyboard.Show(owner). This still doesn't prevent the keyboard from being unable to be used while an OpenFileDialog or SaveFileDialog is in their ShowDialog method.
How can we use an on-screen keyboard form on top of an OpenFileDialog or SaveFileDialog without having the keyboard be hosted in a separate process?
Well, running the OSK window in another process is a fine idea. You get it for free by running osk.exe, provided by Windows. You could technically run it another STA thread but that's a fairly advanced technique, too many ways where the SystemEvents class can seriously ruin your life.
But you can solve the problem with a sliver of code, you just need to re-enable the OSK window right after the dialog is displayed. Elegantly done with the BeginInvoke() method:
private void OpenButton_Click(object sender, EventArgs e) {
this.BeginInvoke(new Action(() => EnableWindow(osk.Handle, true)));
if (openFileDialog1.ShowDialog(this) == DialogResult.OK) {
// etc...
}
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hWnd, bool enable);
With the assumption that the osk variable stores a reference to your OSK form.

How to suppress Disable add-in dialog when Excel is force close

My addin is written in c#, NetOffice, ExcelDNA using WPFframework. Some part uses winforms, too.
The main UI is WPF
When there is a modal dialog displayed, users force close Excel.
Next time when they launch excel, Excel will say " Excel experienced a serious problem with the '*' add-in. If you have seen this message multiple times, you should disable this add0in and checke to see if an update is available. Do you want to disable this add-in?"
Yes, No
Users usually click Yes or enter without reading the message and then my add-in disappears from Excel.
So I do not want this dialog to show up. Is it possible and how? thanks
I try to catch all exception in AutoOpen() like below. But it seems have no effect to stop the dialog at all.
public void AutoOpen()
{
.....
System.Windows.Forms.Application.ThreadException += ApplicationOnThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
....
}
public void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Helper.LogError(e.Exception);
}
public void ApplicationOnThreadException(object sender, ThreadExceptionEventArgs threadExceptionEventArgs)
{
Helper.LogError(threadExceptionEventArgs.Exception);
}
public void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
if (!(args.ExceptionObject is ThreadAbortException))
{
Exception exc = args.ExceptionObject as Exception;
Helper.LogError(exc);
}
}
public void CurrentDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Helper.LogError(e.Exception);
e.Handled = true;
}
I presume by 'users force close Excel' you mean the user ends the Excel process from Task Manager or something.
Excel puts some internal guards in place around ribbon handler calls, so that if Excel crashes during a ribbon event handler, Excel knows which add-in was called when the crash happened, to disable next time as you describe. So if Excel is terminated unexpectedly while your modal dialog is shown, your add-in is the one remembered as the 'cause'.
Your attempt at handling unhandled exceptions is not likely to work, since .NET is hosted in a native process (in Excel). So unhandled exceptions which bubble up to Excel won't be returned to the .NET runtime, but will more likely crash the whole Excel process. So trying to handle more exceptions is not likely to help.
Perhaps a modal dialog is not the right approach, since it causes your users to get confused and think Excel has crashed, causing the unexpected termination. At least be sure to set the Excel window as the parent of the modal dialog, so that the dialog stays in front of Excel.

tapjoy issue with video playing

I am having one Windows phone game, built using Silverlight. In this game, I want to add TapJoy. I have downloaded their latest SDK and follow all their steps to intigrate the it within my app.
In the game, I am using silverlight as a main frame work and Global Media Element to play contious Background Music. I am using
(Microsoft.Xna.Framework.Media) (Microsoft.Xna.Framework) namespace.
Using them, I use following methods to play contious background sound.
DispatcherTimer and FrameworkDispatcher.Update
Now, when I click tap joy button to open their offers, they load fine; however, when I open the video within the offer, they show us following error “Video cannot be played, please try again.”
Based on some research and study, I tried few things and found that,
a) I need to set Media Element and DispatcherTimer is to null.
b) The application is sent in background (deactivated) and then I open it again (activated), the video is coming fine. I checked and found that Media Element and DispatcherTimer were set to null properly.
But if I follow step one only, and do not send the app in background, the media element and dispatcherTimer are not set to null.
Can anyone please help me and answer me following
a) Am I doing anythign wroing with this?
b) Can I do anything so that when tap joy button is clicked, my application is sent to background automatically since this can solve the issue.
c) I am using gc.collect() after setting value to null but still it is not getting destroyed.
Thanks in advance,
David Jacob.
I'm trying to follow along with what you've said. I personally would've set it up differently, but I'll get to that later.
I have a setup that is similar to your description, and it works with Tapjoy's Videos.
Firstly, you mentioned that it was a Silverlight game, so I created a new Windows Phone Application project under the Silverlight For Windows Phone template, in VS 2010.
Setup Dispatcher:
I added the following class to my project (typically called XNAFrameworkDispatcherService.cs from this msdn example: http://msdn.microsoft.com/en-us/library/ff842408.aspx)
public class XNAFrameworkDispatcherService : IApplicationService
{
private DispatcherTimer frameworkDispatcherTimer;
public XNAFrameworkDispatcherService()
{
this.frameworkDispatcherTimer = new DispatcherTimer();
this.frameworkDispatcherTimer.Interval = TimeSpan.FromTicks(333333);
this.frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
FrameworkDispatcher.Update();
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
void IApplicationService.StartService(ApplicationServiceContext context)
{
this.frameworkDispatcherTimer.Start();
}
void IApplicationService.StopService()
{
this.frameworkDispatcherTimer.Stop();
}
}
In order to start this service, make sure you've added it to your App.xaml.
Add an attribute to your Application element that points to your namespace, something like this:
xmlns:s="clr-namespace:WindowsPhoneApplication;assembly=WindowsPhoneApplication">
Then within your block add the following:
<s:XNAFrameworkDispatcherService />
Play Music:
Now about playing a looping music file.
In the MainPage.xaml.cs, I've setup a Microsoft.Xna.Framework.Media.Song to loop when the page is navigated to, using the Microsoft.Xna.Framework.Media.MediaPlayer.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Tapjoy.TapjoyConnect.Instance.RequestTapjoyConnect("your-app-id", "your-secret-key");
try
{
Song song = Song.FromUri("example", new Uri("/example.wma", UriKind.Relative));
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(song);
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Can't load sound");
}
}
I also set it to stop playing music, when the page is navigated away from.
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
MediaPlayer.Stop();
}
I then created a button to launch the Tapjoy Offer wall.
private void button1_Click(object sender, RoutedEventArgs e)
{
Tapjoy.TapjoyConnect.Instance.ShowOffers();
}
Summary:
What happens now, is when your Application starts up, it launches the XNAFrameworkDispatcherService that ticks at approximately 30fps. This will dispatch messages that are in the XNA Framework Queue for you. This is only needed in silverlight applications that are using audio/media services from XNA.
When the MainPage is navigated to, you ping Tapjoy with the Connect call, and you load up your Song to loop.
Normal gameplay can progress now, and when the Show Offers button is clicked, Tapjoy will navigate away from your page, causing on navigated from event to fire, and the MediaPlayer will stop your song.
Ideas for your game:
You might want to consider creating a new project and using the "Windows Phone Silverlight and XNA Application" option. VS2010 will create a blank project with a Content manager already setup, so you can use sounds and images with the XNA pipeline, which I've found to be easier.
Good luck, and remember that Tapjoy provides support for these issues as well. Just email them at support#tapjoy.com, or use the Tapjoy Developer group at: https://groups.google.com/group/tapjoy-developer?hl=en

Go back in a specific panorama/pivot item?

I would like to know if is it possible when a user press "back button" to go in a specific pivot or panorama item on WP7 sdk.
You can make sure that the user is always returned to the item they left by overriding the OnNavigatedFrom and OnNavigatedTo events and using the PhonePageApplication.State property to store the selected item. This will work even if the app is tombstoned while on a different page.
Something like:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
State.Add("selectedPivot", myPivot.SelectedIndex);
base.OnNavigatedFrom(e);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
myPivot.SelectedIndex = (int)State["selectedPivot"];
base.OnNavigatedTo(e);
}
Please note the above is untested, requires additonal checks and error handling, etc. but should be enough to get you started.
It would be possible to implement this approach by implementing the OnBackKeyPress override in your page, however, this would not be consistent with back button behavior in Windows Phone 7 applications. The back button is supposed to only be used for navigating backwards through the application's page stack, and then to leave the application to navigate backwards through the application stack. To implement any other behavior would be counter-intuitive and is also highly likely to fail certification.

How do I capture keystrokes in a Silverlight application?

I am trying to capture any keystroke that happens inside my Silverlight 2 application. There are not any input fields, I'm writing a game, and need to know which of the arrow keys are being pressed. My best guesses at how to capture these through an event handler are unsuccessful. Any recommendations?
Good to see you again (virtually).
I'm assuming you already tried wiring KeyDown on the root UserControl element. Here are some tips:
The plugin needs focused before it sees key events. You'll have to force the user into clicking on the plugin to start.
Make sure you don't have another element (like the ScrollViewer) that is eating arrow keys events. If you have a ScrollViewer in play you'll only be seeing KeyUp.
No switching to full screen mode.
Must be something simple you are missing like that. Hope that helps.
Handle the KeyDown and/or the KeyUp event on your root Grid.
Silverlight 2 supports the KeyUp and KeyDown events (only, I believe - not KeyPress).
In these events, you get a KeyEventArgs object as a parameter. You can get the KeyCode or KeyData from this.
In reviewing a few different threads from different forums regarding this matter it would seem it is best to handle your keyevents on your Page (root) element, parse the key for the desired effect, and redirect your command to the particular control.
Page
this.KeyDown += (s, e) =>
{
MyControl control = (MyControl)Layoutroot.FindName("controlname");
if(control != null)
{
control.MyPublicFunction(e.Key);
}
};
MyControl
public MyPublicFunciton(Key pressedKey)
{
if(pressedKey == Key.Enter)
{
//Do something
}
}

Resources