Give focus to textBox on key press - c#

I want to give a textbox focus when the user starts typing anywhere in my app.
My page inherits from LayoutAwarePage.
Can this be achieved ?
Edit:
I got this code:
// In constructor
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
// Somewhere else in class
void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
this.setSearchboxFocus((int)args.VirtualKey);
}
private void setSearchboxFocus(int keyCode)
{
if (keyCode == 38)
return;
if (keyCode == 40)
return;
if (this.searchBox.FocusState == Windows.UI.Xaml.FocusState.Unfocused)
{
this.searchBox.Text = "";
this.searchBox.Focus(Windows.UI.Xaml.FocusState.Keyboard);
}
}

For anyone reading this thread in the future, it is because of the webview. I asked a similar question on the msdn forum here. As of Windows 8.1, the webview is implemented as a separate window and completely steals all keyboard input when it has focus without passing any of it up to the controlling application. If you are able to change the HTML in the website being called it may be possible to use javascript listeners to pass events between the application and webview, but I did not test this myself. Unfortunately there does not seem to be any other workaround at this time.

You can handle the KeyDown/KeyUp event for the whole page by subscribing to these events
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp

This might help
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
textBox1.Focus();//sets focus to textBox1 when user presses a key on form
}

How about something like this?
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (!textBox1.Focused)
{
textBox1.Focus();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}

How about, on the Windows.UI.Xaml.Controls.Page:
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
textBox1.Focus(Windows.UI.Xaml.FocusState.Keyboard);
base.OnKeyDown(e);
}

Related

How to catch event with hardware back button on xamarin forms?

I know the solution on Android
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
// do something here
return true;
}
return super.onKeyDown(keyCode, event); }
But i cant do it on the forms side. The focus is an Entry so the keyboard is visible and when i press hardware back button (keyboard disappear) i'd like to set my variable value.
Edited:
bool _tapped;
LwTeszt.PropertyChanged += (s, e) =>
{
if (LwTeszt.SelectedItem != null)
{
EntryTeszt.Focus();
}
};
EntryTeszt.Unfocused += EntryTeszt_Unfocus;
private void EntryTeszt_Unfocus(object sender, FocusEventArgs e)
{
_tapped = true;
}
private void ViewCell_Tapped(object sender, EventArgs e)
{
if (_tapped)
{
EntryTeszt.Unfocus();
_tapped = false;
return;
}
EntryTeszt.Focus();
}
Unless you have additional logic that you didn't post I think you might be overcomplicating things. I believe all you need to do is focus your entry on ViewCell_Tapped
private void ViewCell_Tapped(object sender, EventArgs e)
{
EntryTeszt.Focus();
}
Forms will handle unfocusing your Entry for you when back is pressed and in that case you won't need the LwTeszt.PropertyChanged, _tapped, and the EntryTeszt.Unfocused parts.
There is an Event you have to just override that and you can handle back button in Xamarin forms. Use below code for handling back button:
protected override bool OnBackButtonPressed()
{
// your code
return base.OnBackButtonPressed();
}
Also you can refer this question for more information.

How do I create keyboard input in a wpf application?

I want to make a wpf application in c# that displays some text on screen, and where the user is supposed to write a response and press enter to submit the response. I don't want to use a textbox, since there is only one line for the text input in the window, and I don't want the user to have to click to select the textbox. I want the application to be mouse-free.
My question is: How do I make it so that when the user has written their answer, they can submit the response simply by pressing enter?
I have tried the following snippet of code which I found on a microsoft help website:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
doSomething();
}
}
I suppose I have to add some code elsewhere, but I'm not sure where or what I need to add.
If you want to make sure your window process every Enter key press without care what control is focused you can use PreviewKeyDown event:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//Process user input
e.Handled = true;
}
}
Of course if you are doing mvvm you can create a behavior to encapsulate the event handler:
public class WindowBehavior : Behavior<Window>
{
protected override void OnAttached()
{
AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
}
private void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show("Enter from Window");
e.Handled = true;
}
}
protected override void OnDetaching()
{
AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
}
I suggest you to read this article about bubble, tunneling and direct events basic for WPF events.
If you have a button that you're using for submit, you can easily set it as the default by using the IsDefault=true (wrote a tip about doing this and the cancel for the escape here.)
Other than that, you'll have to have somewhere to write it (yet you don't want a textbox? you can select it by default, or tab into it if you don't have the focus there), and you can handle the keydown to "catch" the Enter otherwise.

How to KeyDown event when you have buttons in your form

I made a program in WinForms that shows a blank screen, and then if you press Enter then something happens..
well i used this code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
label1.Visible = false;
Colors.Start();
}
Now when I tried to add some buttons to the blank screen, the option to click on Enter just don't work anymore... no matter what I do. and please don't earse this question, I'm kind of new in programming and I know there's alot of questions like that one, but I couldn't understand them...
thanks
Is the form's AcceptButton property assigned to a button?
If so, that could be grabbing the Enter keystroke first.
An example of the suggestion by Hans Passant:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
MessageBox.Show("Enter");
return true; // optionally prevent further action(s) on Enter; such as Button clicks
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Note that if you return true, then controls like the buttons will not get the Enter keystroke.

How to capture combination of Insert+Tab in WinForms?

This is not a duplicate. Many similar threads discuss capturing a combination involving a modifier key.
I need to get something triggered when a shortcut key (a combination of Insert+Tab) is pressed from a control, say Button.
Catch:
This involves no modifier key like Alt or Shift for which .NET has built in checking.
This has Tab key which is not caught so easily.
What I tried and came close:
1) KeyDown Event but doesnt capture Tabs..
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte[] keystate);
static void form_KeyDown(object sender, KeyEventArgs e)
{
if (!(((Form)sender).ActiveControl is Button))
return;
byte[] keys = new byte[255];
GetKeyboardState(keys);
if (keys[(int)Keys.Insert] == 129 && keys[(int)Keys.Tab] == 129)
{
// doesn't work
}
if (keys[(int)Keys.Insert] == 129 && keys[(int)Keys.J] == 129)
{
// works, since here this doesnt involve Tab
}
}
This works with regular combinations, doesnt fire along with Tab.
2) KeyPreview Event which captures Tab key, but I do not know how to get a combination of keys pressed
static void form_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (!(((Form)sender).ActiveControl is Button))
return;
if (e.KeyCode == Keys.Tab)
//works
if (e.KeyCode == Keys.Insert && e.KeyCode == Keys.Tab)
//doesn't hit.
}
Requirement:
1) I am not registering the event from Form class. Instead I have a utility class which creates all required events (along with other shortcuts). I just pass the instance of form to a static function. So I am quite unsure how I should utilize the various key overriding calls. Here is how I do it:
public frmLogin()
{
InitializeComponent();
Utility.SetFormEvents(this);
}
static void SetFormEvents(Form f){
//foreach control...........
}
But I can give up on this..
Thanks..
Tab is considered a command key, you don't actually get notified of it being pressed directly. You could PInvoke the GetKeyState method, but I think it's just easier to recognize that tab is a command key (and override ProcessCmdKey) and keep track of whether the Insert key is up or down. For example:
static bool insertPressed;
static bool tabPressed;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData == Keys.Tab)
{
tabPressed = true;
CheckForTabAndInsert();
}
return base.ProcessCmdKey(ref msg, keyData);
}
static void form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
insertPressed = true;
CheckForTabAndInsert();
insertPressed = false;
}
}
static void form_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert) insertPressed = false;
}
The drawback is that you only really get a KeyPress for tab with ProcessCmdKey, so you can only really support Insert+Tab (not Tab+Insert). This is because Tab is used to switch context from one control to another. Depending on your situation (i.e. in the context of a text box), you could make use of the AcceptTab property to possibly just use KeyUp and KeyDown... But, from what you posted, that doesn't appear to be the case.

DataGridView keydown event not working in C#

DataGridView keydown event is not working when I am editing text inside a cell.
I am assigning shortcut Alt+S to save the data, it works when cell is not in edit mode, but if it is in edit mode below code is not working
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Alt | Keys.S))
{
//save data
}
}
Whenever a cell is in edit mode, its hosted control is receiving the KeyDown event instead of the parent DataGridView that contains it. That's why your keyboard shortcut is working whenever a cell is not in edit mode (even if it is selected), because your DataGridView control itself receives the KeyDown event. However, when you are in edit mode, the edit control contained by the cell is receiving the event, and nothing happens because it doesn't have your custom handler routine attached to it.
I have spent way too much time tweaking the standard DataGridView control to handle edit commits the way I want it to, and I found that the easiest way to get around this phenomenon is by subclassing the existing DataGridView control and overriding its ProcessCmdKey function. Whatever custom code that you put in here will run whenever a key is pressed on top of the DataGridView, regardless of whether or not it is in edit mode.
For example, you could do something like this:
class MyDataGridView : System.Windows.Forms.DataGridView
{
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
MessageBox.Show("Key Press Detected");
if ((keyData == (Keys.Alt | Keys.S)))
{
//Save data
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Also see related, though somewhat older, article: How to trap keystrokes in controls by using Visual C#
Another way of doing it is by using the EditingControlShowing event to redirect the event handling to a custom event handler as below:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl tb)
{
tb.KeyDown -= dataGridView1_KeyDown;
tb.KeyDown += dataGridView1_KeyDown;
}
}
//then in your keydown event handler, execute your code
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Alt | Keys.S))
{
//save data
}
}
This is true that EditingControlShowing can help, but not if you wants to catch the Enter key. In that case, one should use the following method:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl tb = e.Control as DataGridViewTextBoxEditingControl;
tb.KeyDown -= dataGridView_KeyDown;
tb.PreviewKeyDown -= dataGridView_PreviewKeyDown;
tb.KeyDown += dataGridView_KeyDown;
tb.PreviewKeyDown += dataGridView_PreviewKeyDown;
}
}
void dataGridView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
<your logic goes here>
}
}
A simpler way I just tried out is as follows:
Set the KeyPreview property of the Form to true.
Instead of catching the KeyDown event on Grid, catch the KeyDown event on Form.
Code as follows:
Private Sub form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If grd.Focused Then
'Do your work
End If
End Sub
I worked with this
private void grdViewOrderDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
grdViewOrderDetail_KeyDown(null,null);
}
private void grdViewOrderDetail_KeyDown(object sender, KeyEventArgs e)
{
//Code
}
The solution
class MyDataGridView : System.Windows.Forms.DataGridView {
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) {
if ( keyData == Keys.Enter ) {
.
Process Enter Key
.
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Worked perfectly for me
use PreviewKeyDown event
private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}

Categories

Resources