ToolStripMenuItem.ShortcutKeys not working unless menu has focus - winforms

I have a form with a MainMenuStrip. For some ToolStripMenuItems in this menu strip I have set a ShortcutKeys. However, using this key shortcut only works as long as as my menu strip has focus.
Is this the expected behavior? I thought these shortcuts should work no matter where the focus was?
Thanks.

Here is the code, this example is using - 'Enter' key as shortcut - you can put yours.
Override following event in your form.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
//write code for your shortcut action
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}

Related

WPF send key to textBox

I'm working on a virtual keyboard, but i struggle to send Keys. Nothing happens, except when i hard-add them to the textbox. Here's my code
public static void Send(Key key)
{ //Found online
var e = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key)
{
RoutedEvent = Keyboard.KeyDownEvent
};
InputManager.Current.ProcessInput(e);
}
private void ClickOnKey(object sender, RoutedEventArgs e)
{
CustomButton cb = sender as CustomButton;
string text = cb.text;
Console.WriteLine(text);
element_to_focus.Focus(); //The textbox
Send(translate_string_to_key(text));
}
ProcessInput seems to only raise the appropriate key-related events, but will not actually modify the text.
If you really want to simulate key presses, you'll need to leverage p/invoke and use SendInput. Luckily, someone's already done the p/invoke work for us and has made their work available:
https://archive.codeplex.com/?p=inputsimulator
It's also available as a NuGet package (I found two versions):
https://www.nuget.org/packages/InputSimulator/
https://www.nuget.org/packages/InputSimulatorPlus/

How to determine if a Picker was ended by pressing Cancel or Done?

I'm using the Pickers to implement the following behavior: if the user has not previously entered a value, the Picker is shown as blank (except an edit button [>]). If the user presses the edit button the Picker is set to a reasonable default value (by overriding Picker.pressed()), which the user can then keep or change. If the user presses Done, the edited value is kept and stored.
However, I can't figure out how to detect if the user presses Cancel, in which case the underlying value edited by the Picker should be left with same undefined value it had before launching the Picker (e.g. typically a duration of 0 or a Date(0)).
Is there a way to detect how the user ended the Picker? If not, any suggestions for how I might implement the behavior I want?
I found a way to do this that works at least for my use case (not sure it it covers all situations). Since pressing Cancel is the same as NOT pressing Done, I detect if Done has been pressed via an actionlistener and the variable inputValidated and if not, return the old value when getDate() (or getDuration(), getValue() etc) is called. If someone else needs this, here's the essence of the code:
private boolean inputValidated; //true if the user explicitely validated the value by pressing Done?
//in the constructor:
addActionListener((e) -> {
inputValidated = true;
});
#Override
public void pressed() {
if (getDate() == null) {
if (defaultDate != null) {
inputValidated=false;
setDate(defaultDate);
}
}
super.pressed();
}
#Override
public Date getDate() {
if (inputValidated) {
return super.getDate();
} else {
return null;
}
}

Cannot access native WpfButton in UI Test, get Exception: System.NotSupportedExceptions

I'm trying to access a native Wpf control property within the UI test framework (MS UI Tests). My specific issue is that, when I try accessing a WpfButton control property (e.g., IsVisible) using the function call WpfButtonObject.GetProperty("IsVisible"), the exception "System.NotSupportedExceptions" occurs. I'm able to see this WpfButton property using Snoop; so, I'm wondering if the GetProperty call is correct? Please see my related code below. Thanks for any insight.
UIMap.cs: Test function for a pressing a WpfButton. Please note the call uIButton.GetPropery("IsVisible"). This is where the exception occurs:
public void PressButtonTest()
{
WpfButton uIButton = this.UIMainWindowWindow.UIButtonButton;
object state = uIButton.GetProperty("IsVisible"); // Throws SystemNotSupportedException exception
bool stateBool = (bool)state;
Assert.IsTrue(stateBool, "Button is visible");
PressButton();
}
UIMap.Designer.cs: WpfButton property:
public WpfButton UIButtonButton
{
get
{
if ((this.mUIButtonButton == null))
{
this.mUIButtonButton = new WpfButton(this);
#region Search Criteria
this.mUIButtonButton.SearchProperties[WpfButton.PropertyNames.AutomationId] = "button";
this.mUIButtonButton.WindowTitles.Add("MainWindow");
#endregion
}
return this.mUIButtonButton;
}
}
Here's what I've done:
Point point;
bool isClickable = uIButton.TryGetClickablePoint(out point);
Assert.IsTrue(isClickable, "No clickable point was found, button not visible.");
By the way, your message in your Assert (2nd parameter) is inaccurate because it's only used on fail... in your case, when the button would not be visible. So in your output it would say "Button is visible" on failure when in fact it was not.

How to get CheckBox state changed for multiple checkboxes?

I need to implement somethingh like this, if user will select one checkbox it will hide some component from UI, if user will select another checkbox it will hide some different components from UI. I have implemented this using onCheckedChanged Listner.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
switch (buttonView.getId()){
case R.id.checkbox_regread:
if(isChecked){
btn_reg_rw.setText("Read");
cb_reg_write.setEnabled(false);
}else{
cb_reg_write.setEnabled(true);
}
break;
case R.id.checkbox_regwrite:
if(isChecked){
btn_reg_rw.setText("Write");
cb_reg_read.setEnabled(false);
}else{
cb_reg_read.setEnabled(true);
cb_reg_read.setChecked(false);
}
break;
}
But problem i am facing is that i getting the event for checkbox_rewrite but not able to get the event for R.id.checkbox_regread:. I have check with the Ids, they are correct.
give me any idea why this is happening?
Thanks,

WinForms, Handling all keys = OnKeyPress + OnKeyDown, but how?

I've got one Form, custom drawing, no controls.
When I need to get the input from the user I go to OnKeyDown event and then map event's KeyData to a string** - so that I can recognize that user has pressed "ctrl X", etc, so everything is almost ok... the problem is with different keyboard settings and language specific letters - so for today my users get
ã -> a
ó -> o
So I need the KeyPress event right? But how do I know that user typed in for example 'ł' and not alt+L? I can't get my head around that for a while now...
** - I need to do it like that since I let users to configure shortcuts and using .ToString() produces not so user friendly text like "OemPeriod, Control" or even better: "ControlKey, Control"
Yes, you'll need the KeyPress event. Or rather, override OnKeyPress. Mapping virtual key codes in the KeyDown event to key strokes is quite difficult, you'd have to be aware of the current keyboard layout. Take a look at the MSDN docs for ToUnicodeEx() to see what you are up against.
You don't have to worry about keystroke combinations like Alt+L. They don't generate a KeyPress event.
Here's an example. Start a new Windows Forms project and make the code look like this:
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
StringBuilder mText = new StringBuilder();
protected override void OnKeyPress(KeyPressEventArgs e) {
if (e.KeyChar == '\b') {
if (mText.Length > 0) mText.Remove(mText.Length - 1, 1);
}
else mText.Append(e.KeyChar);
Invalidate();
}
protected override void OnPaint(PaintEventArgs e) {
TextFormatFlags fmt = TextFormatFlags.Left;
TextRenderer.DrawText(e.Graphics, mText.ToString(), this.Font, this.ClientRectangle, Color.Black, fmt);
}
}
}

Resources