How to use Numlock keys in calculator - c#

I was writing a program of simple calculator. I was able to make the calculator, but the entering is through mouse clicks.
I wanted to know how to use numlock keys for entering numbers.

It can get a little tedious, but assuming your application is WPF, here's the overview of user input from MSDN.
The important part is that your window definition (the XAML) can get a KeyDown event handler assigned. If you add it, when you hit =, you should be given the opportunity to have the method created. Do that, and you can figure out what key was pressed and what to do about it. The MSDN example of it looks like this:
private void OnButtonKeyDown(object sender, KeyEventArgs e)
{
Button source = e.Source as Button;
if (source != null)
{
if (e.Key == Key.Left)
{
source.Background = Brushes.LemonChiffon;
}
else
{
source.Background = Brushes.AliceBlue;
}
}
}
I don't recommend the color thing, myself, but you can connect the logic you use for your buttons, instead, too, if you wanted.

Related

How to PgUp/PgDn with SendKeys to a foreground textbox

I am trying to page up/down the contents of a simple textbox control in a simple Windows Form on NET 6.0, but something is wrong. Textbox shortcuts are enabled (probably why SendKeys.SendWait("^a"); works) and readonly is false.
I have a method (not on the UI thread) that I call to SendKeys.SendWait("{PgUp}"); to the foreground app (which is both the key sender and textbox (with focus) receiver.
If I type PgUp on the keyboard, the textbox pages up as expected.
If I SendKeys.SendWait("^a");, the textbox selects all text as expected.
If I Sendkeys.SendWait("{PgUp}");, the textbox adds a blank line to the bottom of the text.
From this I conclude that my code is working because it sends "^a" and the textbox receives it and selects all text. But somehow the textbox does not handle the "{PgUp}" key, even though it does when the PgUp key is sent by the keyboard.
I've read easily a dozen articles and posts on the web and SO that talk about paging using scrolling events, positioning the caret and then scrolling to the caret, and so on. But none of them say anything about why SendKeys(^a) and keyboard PgUp would work but SendKeys.SendWait("{PgUp}") would fail.
Can anyone tell me what I'm doing wrong and maybe what I need to do (or read) to fix it? Thank you
UPDATE: Jimi asked for some code, so here is the code that I use to send the ^a and the {PgUp} keys. I know this is not on the UI thread because it is executed from a voice-driven recognizer thread. The app is a voice-driven app that displays content in the textbox by textbox.AppendLines calls. I was trying to PgUp and PgDn the multi-line textbox by voice as well.
When I tried to use Send (I normally use .SendWait for everything in other programs), I received the following error message:
System.InvalidOperationException: 'SendKeys cannot run inside this
application because the application is not handling Windows messages.
Either change the application to handle messages, or use the
SendKeys.SendWait method.'
It is true that my app does not intercept Windows messages. I can't figure out why the app can receive and properly process my keyboard keys, and my "^a' shortcut keys, but not the SendWait("{PgUp}") key.
internal static void
HelperPageUp() {
var keys = "{PgUp}";
keys = "^a";
SendKeys.SendWait(keys);
}
I'm starting to think that {PgUp} is never handled by a textbox or control. Instead, probably {PgUp} must be handled by logic in a case statement that converts PgUp "orders" into sets of actions that implement whatever PgUp means to the app that receives the PgUp key. So maybe I will have to add a keystroke handler to the form. Maybe something like this:
textBox1_KeyUp(object sender, KeyEventArgs e) {
// identify the special key and implement what it means
if (e.KeyCode == Keys.PageDown) {
...
e.Handled = true;
}
Yes, my thought at the end of the question was correct. The ^a was handled by the textbox because I had textbox.EnableShortcuts=true;, so the textbox handled the popular ^a shortcut. But keys like {PgUp} are a different matter; they are not included in shortcuts.
The solution was to write code to handle the {PgUp} key explicitly in the form. Here is my code that worked.
void
textBox1_KeyUp(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.PageUp) {
// page the viewport up; watch for end of content
var charIndex = textBox1.SelectionStart;
var lineIndex = textBox1.GetLineFromCharIndex(charIndex);
// move 20 lines up, but not past zero
var newLine = lineIndex - 20;
var newIndex = Math.Max(0, newLine);
// set the new anchor and scroll to it
var newAnchor = textBox1.GetFirstCharIndexFromLine(newIndex);
textBox1.Select(newAnchor,0);
textBox1.ScrollToCaret();
e.Handled = true;
}

Attempting to make my program automatically tab to next input field (Windows Forms)

Currently making a program which requires the input of a field which is made up of several components. I have broken them down into their unique parts, and I want to make my code work such that when the user has input the required characters it automatically moves such that they are writing the rest of the code in the following text box.
My code so far is:
{
InitializeComponent();
if (textBox1.Text.Length == 2)
textBox2.Select();
textBox2.Focus();
if (textBox2.Text.Length == 3)
textBox3.Select();
textBox3.Focus();
if (textBox3.Text.Length == 2)
textBox4.Select();
textBox4.Focus();
}
I'm sure I probably have this in the wrong location, but I am new to C# and hence a massive newb. Any help would be greatly appreciated because at the moment this isn't working and it is massively annoying.
If you call this on Form's constructor, it won't do anything, when Form the constructor works the length of all textboxes are 0. You need some events like textbox's TextChanged. Because you need to focus next textbox, after some text has written. So something like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length == 4)
{
textBox2.Focus();
}
...
}
Hope helps,

Control input via button

I made a Tic Tac Toe game and I'm trying to add a few features.
I was used to handle the taken buttons with
button.enabled=false;
The problems is that the text on the buttons turns grey.
So I made a button click for each button:
A1_Click, A2_Click, and so on
This is my code into A1_click, and it's the same for the other buttons, the only thing that changes is "A1", "A2", and so on
Button b = (Button)sender;
if (!A1.Text.Equals(""))
{
MessageBox.Show("Not A Valid Input");
}
I get "not a valid input" when I click a button I've already clicked before, I'd just like to be able to click an another button.
I don't want to lose my turn if I click on an already taken button
Based on what I have read I think I know what you are looking for. You are looking for a way to force the user to lose a turn when they click a button that has already been taken, and you do not want to set the enabled property to false. If that is what you want, then I might have some code that could help. First if you are assigning the same click event to multiple buttons with different functions you should try something like this:
for (int i = 1; i < 10; i++)
{
string currentButtonName = "A" + i;
Control currentButton = this.Controls.Find(currentButtonName, true).FirstOrDefault();
currentButton.Click += OnGameButton_Click;
}
What this is doing is searching your form for a control that has a specified name, and since your buttons have a similar name we can easily search for them. Then we can bind a specific function to all of them so that instead of 9 functions to modify you only have 1, and you can validate that they all work the same. Here is the OnGameButton_Click() event code:
private void OnGameButton_Click(object sender, EventArgs e)
{
if (!hasGameStarted || shouldLoseTurn)
return;
// This is the current button user pressed
Button b = (sender as Button);
if (b.Name.Contains('A') && b.Enabled)
{
if (!b.Text.Equals(""))
{
MessageBox.Show("Not A Valid Input! You have lost your turn.");
shouldLoseTurn = true;
}
else
{
b.Text = currentPlayersLetter;
shouldLoseTurn = false;
}
}
}
As you can see with some flags we can monitor the game, and force the buttons to react accordingly take a look at the beginning of the function. We have to validate that the game is engaged, and that the current user has not lost their turn due to pressing the same button. From there we just need modify what you had so that if they do press the same button twice then we modify the shouldLoseTurn flag as needed.
The other approach is to just simply use the Button.Enabled property to disable the button from use. I know you do not what the button to be grayed out, but if you create your own style guide for the button you could make it how you want. This can be challenging though because you will have to modify the default style template for the button to achieve this. Here is another question that discusses just that here

Why does pressing Ctrl+"+" produce a beep in a TextBox?

I am Working with C# and Windows Forms and want to use Ctrl+"Oemplus" as a function key for my application. I use a German keyboard and this key is located 2 keys right of the letter P (that ist then "+"). Whenever I press this key in combination with Ctrl and the focus is on a TextBox I get a beep.
This also happens when I switch to an US keyboard layout (still using my German keyboard). This is then the ] key.
The same happens when pressing this key while in Internet Explorers address bar.
My question is:
Why does this key combination produce a beep in a TextBox.
How can I avoid the beep?
Thanks for any efforts you put on this.
Update:
I tried it on an US/Thai keyboard and get the beep as well. This happens no matter what logical keyboard layout I use (German, US, Thai).
The beep also happens in Windows Explorer in the address bar but not in the search box.
It is very unclear what you hope to happen when you press that keystroke. TextBox leaves no doubt about it, it BEEPs! because it can see that the user is trying to do something special but it doesn't know exactly what. Good reason to beep you. Solution is to implement magic, in the //.. comment in this next snippet. With the extra code to stop the beep at the end:
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == (Keys.Control | Keys.Oemplus)) {
// Invoke magic
//...
// Magic is done now:
e.Handled = e.SuppressKeyPress = true;
}
}
What I believe is happening is that the key combination is not allowed for the Textbox, therefore you are getting the error. You can test for the Key Combination by this code( using the right bracket key in EN Windows) it is using SuppressKeyPress to prevent the Key Combination from being passed to the underlying control to prevent the beep.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (ModifierKeys == Keys.Control)
if (e.KeyValue == 221) // You may need to determine this value for your keyboard layout.
{
textBox1.Text += " + "; // Handle the Key combination.
e.SuppressKeyPress = true; // Prevents key from being passed to underlying control
}
}
After some time I came back on this. What I found unsatisfying with the previous solution was that every TextBox would need that handling for every 'beeping' key I use for something else. Sure I could subclass the TextBox but still I would have two places to change for every key with this behavior (the handling and the beep suppression).
Actually I use Ctrl+'+' as a command key. I did this with a global keyboard hook because the action should be available on and impact all forms.
Instead I handle this now in a base form using the following code:
// Avoid beep on Ctrl+'+' in TextBox.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
Keys key = keyData & Keys.KeyCode;
bool alt = keyData.HasFlag(Keys.Alt);
bool shift = keyData.HasFlag(Keys.Shift);
bool control = keyData.HasFlag(Keys.Control);
if (key == Keys.Oemplus && !shift && control && !alt)
{
// Perform the action for Ctrl+'+'
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
For me this seems the "correct" Position and way to handle a command key. The beep is gone without any additional handling and I don't have to worry if additional command keys produce a beep or not.
When the form had a menu or toolbar this would be handled automatically by the shortcut defined for the menu item. But my forms don't have a menu or toolbar.

Why are some textboxes not accepting Control + A shortcut to select all by default

I have found a few textboxes here and there in my program that accepts Control+A shortcut to select the entire text "by default" with "no coding".
I don't know what additional information I have to give here to enable it for all of them, as I find absolutely no difference between these textboxes. They are all simple dragged and dropped textboxes.
Note: I'm not talking about this piece of code:
if (e.Control && e.KeyCode == Keys.A)
{
textBox1.SelectAll();
}
I want selection by default... or is there anyway to change textbox property so that textboxes accept all default windows shortcuts?
Everything else (Control + Z, Control + X, Control + C, Control + V) works by default! Why not Control + A?
Update: The text boxes that accepted Ctrl+A by default were masked textboxes, not the regular one. And at that point I was with .NET 2.0. But I guess the original problem was something else, as I can see Ctrl+A working fine by default in .NET 2.0 code.
You might be looking for the ShortcutsEnabled property. Setting it to true would allow your text boxes to implement the Ctrl+A shortcut (among others). From the documentation:
Use the ShortcutsEnabled property to
enable or disable the following
shortcut key combinations:
CTRL+Z
CTRL+E
CTRL+C
CTRL+Y
CTRL+X
CTRL+BACKSPACE
CTRL+V
CTRL+DELETE
CTRL+A
SHIFT+DELETE
CTRL+L
SHIFT+INSERT
CTRL+R
However, the documentation states:
The TextBox control does not support the CTRL+A shortcut key when the Multiline property value is true.
You will probably have to use another subclass of TextBoxBase, such as RichTextBox, for that to work.
Indeed CTRL + A will not work unless you add something like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.A))
{
if (sender != null)
((TextBox)sender).SelectAll();
e.Handled = true;
}
}
This answer worked for me in a similar question (which isn't marked as accepted)
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
var keyCode = (Keys) (msg.WParam.ToInt32() &
Convert.ToInt32(Keys.KeyCode));
if ((msg.Msg == WM_KEYDOWN && keyCode == Keys.A)
&& (ModifierKeys == Keys.Control)
&& txtYourTextBox.Focused)
{
txtYourTextBox.SelectAll();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Original Post: How can I allow ctrl+a with TextBox in winform?
Make sure that
Application.EnableVisualStyles();
is not commented out in
static void Main()
That can disable Ctrl+A
This question wants an answer that cannot be given in the form of code avoidance, as the Win32 API at the core of the other methods doesn't allow it. If other methods DO allow it, they are just writing the code for you. :)
So the real question is: What is the smallest, neatest way to do it? This worked for me:
First, there is no need to handle WM_KEYDOWN! And no need to test for the Ctrl key already down either. I know that most examples here (and CodeProject and many other places) all say there is, but it does not cure the beep that results whenever a WM_CHAR arises that is not handled.
Instead, try handling WM_CHAR and doing the Ctrl+A selection there:
LRESULT CALLBACK Edit_Prc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam){
if(msg==WM_CHAR&&wParam==1){SendMessage(hwnd,EM_SETSEL,0,-1); return 1;}
else return CallWindowProc((void*)WPA,hwnd,msg,wParam,lParam);
}
Remember to subclass the EDIT control to this Edit_Prc() using WPA=SetWindowLong(...) where WPA is the window procedure address for CallWindowProc(...)

Categories