Handling VirtualKey in Windows 8 Store Apps with C# - windows-8

I'm aware of how to handle key events, i.e.
private void Page_KeyUp(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case Windows.System.VirtualKey.Enter:
// handler for enter key
break;
case Windows.System.VirtualKey.A:
// handler for A key
break;
default:
break;
}
}
But what if I need to discern between lower-case 'a' and upper-case 'A'? Also, what if I want to handle keys like the percent sign '%'?

Got an answer elsewhere. For those that are interested...
public Foo()
{
this.InitializeComponent();
Window.Current.CoreWindow.CharacterReceived += KeyPress;
}
void KeyPress(CoreWindow sender, CharacterReceivedEventArgs args)
{
args.Handled = true;
Debug.WriteLine("KeyPress " + Convert.ToChar(args.KeyCode));
return;
}
Even better, move the Window.Current.CoreWindow.CharacterReceived += KeyPress; into a GotFocus event handler, and add Window.Current.CoreWindow.CharacterReceived -= KeyPress; into a LostFocus event handler.

You can't easily get this information from KeyUp because KeyUp only knows which keys are being pressed, not which letters are being typed. You could check for the shift key being down and you could also try to track caps lock yourself. Better you use TextChanged event.

Related

Best way "select all" on a *form*? [duplicate]

I'm looking for a best way to implement common Windows keyboard shortcuts (for example Ctrl+F, Ctrl+N) in my Windows Forms application in C#.
The application has a main form which hosts many child forms (one at a time). When a user hits Ctrl+F, I'd like to show a custom search form. The search form would depend on the current open child form in the application.
I was thinking of using something like this in the ChildForm_KeyDown event:
if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
// Show search form
But this doesn't work. The event doesn't even fire when you press a key. What is the solution?
You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
On your Main form
Set KeyPreview to True
Add KeyDown event handler with the following code
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.N)
{
SearchForm searchForm = new SearchForm();
searchForm.Show();
}
}
The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click event handler of that menu entry.
You can even try this example:
public class MDIParent : System.Windows.Forms.Form
{
public bool NextTab()
{
// some code
}
public bool PreviousTab()
{
// some code
}
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.Control | Keys.Tab:
{
NextTab();
return true;
}
case Keys.Control | Keys.Shift | Keys.Tab:
{
PreviousTab();
return true;
}
}
return base.ProcessCmdKey(ref message, keys);
}
}
public class mySecondForm : System.Windows.Forms.Form
{
// some code...
}
If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.
If not, you could create one and set its visible property to false.
From the main Form, you have to:
Be sure you set KeyPreview to true( TRUE by default)
Add MainForm_KeyDown(..) - by which you can set here any shortcuts you want.
Additionally,I have found this on google and I wanted to share this to those who are still searching for answers. (for global)
I think you have to be using user32.dll
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
Further read this http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/
Hans's answer could be made a little easier for someone new to this, so here is my version.
You do not need to fool with KeyPreview, leave it set to false. To use the code below, just paste it below your form1_load and run with F5 to see it work:
protected override void OnKeyPress(KeyPressEventArgs ex)
{
string xo = ex.KeyChar.ToString();
if (xo == "q") //You pressed "q" key on the keyboard
{
Form2 f2 = new Form2();
f2.Show();
}
}
In WinForm, we can always get the Control Key status by:
bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;
The VB.NET version of Hans' answer.
(There's a ProcessCmdKey function template in Visual Studio.)
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If (keyData = (Keys.Control Or Keys.F)) Then
' call your sub here, like
SearchDialog()
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
End Class

Manipulation events of MediaElement not fire when on FullWindows mode

When I set player not in fullscreen (player.IsFullWindows = false), event work normally but when change player to full screen all manipulation event not work. Anyone have solution?
<MediaElement Name="player"
Margin="10,5" ManipulationCompleted="player_ManipulationCompleted"
ManipulationDelta="Grid_ManipulationDelta"
ManipulationMode="TranslateX"
>
I can reproduce this scenario by enabling both the IsFullWindow="True" and the AreTransportControlsEnabled="True". I think it makes sense, because when we are in the Full Window mode, it will go to the new layer named FullWindowMediaRoot instead of the MediaElement. Inside the FullWindowMediaRoot, it is the MediaTransportControls. You can see that clearly by using the Live Visual Tree as following:
So when we are in the Full Window mode, we need to handle the manipulation event of the TransportControls instead of the manipulation event of the MediaElement as following:
public MainPage()
{
this.InitializeComponent();
player.TransportControls.ManipulationMode = ManipulationModes.TranslateX;
player.TransportControls.ManipulationDelta += TransportControls_ManipulationDelta;
player.TransportControls.ManipulationCompleted += TransportControls_ManipulationCompleted;
}
private void TransportControls_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
}
private void TransportControls_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
}
Thanks.

How to delete KeyValue in Visual studio 2012 c++ richTextBox

How i can delete the key which presente "Enter"?? I want the programme show "Plase enter Espace or Tab" when the user tape Enter and then delete this Enter Key. Thank you!
private: System::Void richTextBoxCommentaire_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if (e->KeyValue == (char)13)
{
MessageBox::Show ("Please enter Espace or Tab");
//To delete this Key??
}
}
sorry, using the previewKeyDown should have worked but try the next method :
Use the KeyDown event to filter the desired keys by setting the suppressKeyPress to true as you can see in the example below (the example is in C# for readability but conversion to C++ CLI should be trivial :) :
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = e.KeyCode == Keys.Enter;
}

Number of Touchpoints in GestureRecognizer

I am using the GestureRecognizer to detect drag and pinch gestures.
The ManipulationStarted, ManipulationUpdated and ManipulationCompleted events provide the translation and scale values that are needed to pinch and drag.
However I cant figure out how to distinguish between drag (1 touch point) and pinch (2 touch points) gestures. There is no information about the number of touchpoints in GestureRecognizer.
How can I distinguish between drag and pinch with the GestureRecognizer?
Well, I feel it is very hacky (as most solutions seem to be for a useable WinRT app) but you can create a List<uint> to keep track of the number of pointers that are currently down on the screen. You would have to handle the PointerPressed event on whatever control you are interacting with (Let's say you are using a Canvas) to "capture" the pointers as they are pressed. That is where you would populate the List<uint>. Don't forget to clear the list at the end of the ManipulationCompleted event as well as any event that would fire upon the end of any gestures (like PointerReleased, PointerCanceled, and PointerCaptureLost). Maybe it would be a good idea to make sure the list is cleared in the ManipulationStarted event. Perhaps you can try that and see how that works for you.
In the ManipulationCompleted event, you can check if your List contains exactly 2 elements (PointerIds). If so, then you know it is a pinch/zoom.
Here is what it could look like:
private void Canvas_PointerPressed(object sender, PointerRoutedEventArgs e)
{
var ps = e.GetIntermediatePoints(null);
if (ps != null && ps.Count > 0)
{
this.gestureRecognizer.ProcessDownEvent(ps[0]);
this.pointerList.Add(e.Pointer.PointerId);
e.Handled = true;
}
}
private void gestureRecognizer_ManipulationCompleted(GestureRecognizer sender, ManipulationCompletedEventArgs args)
{
if (this.pointerList.Count == 2)
{
// This could be your pinch or zoom.
}
else
{
// This could be your drag.
}
// Don't forget to clear the list.
this.pointerList.Clear();
}
// Make sure you clear your list in whatever events make sense.
private void Canvas_PointerReleased(object sender, PointerRoutedEventArgs e)
{
this.pointerList.Clear();
}
private void Canvas_PointerCanceled(object sender, PointerRoutedEventArgs e)
{
this.pointerList.Clear();
}
I have been struggling with the same question for a few hours now and it looks WinRT platform does not provide that. What it instead provides is Delta.Rotation and Delta.Scale values in addition to Delta.Translation with the arguments to ManipulationUpdated callback.
If Delta.Rotation is 0 (or very close to zero - because it is a float value) and Delta.Scale is 1 (or very close to 1), you can conclude that a pinch operation is not the case and a drag operation is being carried otherwise it is a pinch operation. It is not the best you can get but it looks it is the only availability for the time being.

Removing all event handlers in one go

Problem: I have a document class which contains a list of objects. These objects raise events such as SolutionExpired, DisplayExpired etc. The document needs to respond to this.
Documents can sometimes exchange objects, but a single object should never be 'part' of more than one document.
My document class contains a bunch of methods which serve as event handlers. Whenever an object enters the document, I use AddHandler to set up the events, and whenever an object is removed from the document I use RemoveHandler to undo the damage. However, there are cases where it's difficult to make sure all the steps are properly taken and I might thus end up with rogue event handlers.
Long story short; how do I remove all the handlers that are pointing to a specific method? Note, I don't have a list of potential event sources, these could be stored anywhere.
Something like:
RemoveHandler *.SolutionExpired, AddressOf DefObj_SolutionExpired
You can use Delegate.RemoveAll(). (The part you're interested in is in button2_Click)
public void Form_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
TestEvent += new EventHandler(Form_TestEvent);
}
event EventHandler TestEvent;
void OnTestEvent(EventArgs e)
{
if (TestEvent != null)
TestEvent(this, e);
}
void Form_TestEvent(object sender, EventArgs e)
{
MessageBox.Show("TestEvent fired");
}
void button2_Click(object sender, EventArgs e)
{
Delegate d = TestEvent as Delegate;
TestEvent = Delegate.RemoveAll(d, d) as EventHandler;
}
void button1_Click(object sender, EventArgs e)
{
OnTestEvent(EventArgs.Empty);
}
You should note that it doesn't alter the contents of the delegates you pass in to it, it returns an altered delegate. Consequently, you won't be able to alter the events on a button you've dropped on a form from the form, as button1.Click can only have += or -= used on it, not =. This won't compile:
button1.Click = Delegate.RemoveAll(d, d) as EventHandler;
Also, be sure that wherever you're implementing this you're watching out for the potential of race conditions. You could end up with some really strange behavior if you're removing handlers from an event that is being called by another thread!
public class TheAnswer
{
public event EventHandler MyEvent = delegate { };
public void RemoveFromMyEvent(string methodName)
{
foreach (var handler in MyEvent.GetInvocationList())
{
if (handler.Method.Name == methodName)
{
MyEvent -= (EventHandler)handler;
}
}
}
}
EDIT 2: Apologies for my misunderstanding--I see that you were pretty clear about not having access to the event sources in your original post.
The simplest way I can think of to solve this problem involves implementing a Shared dictionary of object-to-document bindings. When an object enters a document, check the dictionary for an existing binding to another document; if present, remove handlers that refer to the old document before adding them for the new. Either way, update the dictionary with the new binding.
I think in most cases the performance and memory impacts would be negligible: unless you're dealing with many tens of thousands of small objects and frequently exchange them between documents, the memory overhead of each key/value pair and performance hit for each lookup operation should be fairly small.
As an alternative: if you can detect (in the document event handlers) that the sender of the event is no longer relevant to the document, you can detach the events there.
These seem like the kind of ideas you might have already rejected--but maybe not!
Use Delegate.RemoveAll (maybe using reflection if the Delegate instance is private).