473,587 Members | 2,541 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Clear keyboard buffer

I've got a very large C# forms app and now that its being used in
bigger environments we're getting a steady stream of "why does it do
this?" problems. The most nagging of which right now is that when a
MessageBox.Show () is displayed, if the user hits enter or esc, those
keys get passed back to the form. From searching online, this is
apparently by design(for whom, I don't know, why its not optional, I
_really_ don't know). This software was designed for users who are
more used to the keyboard than the mouse and so every form has keyboard
hooks. So I thought to myself, rather than dig through all 12 megs of
source code, why don't I just clear the keyboard buffer and do
something like this:

public class MessageBox
{
private static void KillKeys()
{
// clear the keyboard buffer
}
public static DialogResult Show(string text)
{
DialogResult r=System.Window s.Forms.Message Box.Show(text);
KillKeys();
return(r);
}
// implement all other Show() methods
}

But, I'm unable to find anything, anywhere, that tells me how to clear
the keyboard buffer. The recommendations I've seen online are for
console apps. Is there anyway to clear the keyboard buffer in C# for
winforms?

Nov 17 '05 #1
5 21050

Clear keyboard buffer?? Oh wait I can help here... Hang on... Digging...
Clear buffer.. I think you just read keys until empty but I know I hacked
that up... Must've been back when I was with that hot red head... Back when
rates were pretty good... I think it was... Ahhh, here it is:

Uhhm, it's in pieces because it was coded as part of a larger library, also
you need the import dll installed on the machine - I think it is installed on
most machines by default, if not you'll have to import the _kbhit() &
_getwch() functions from one of the other standard C runtime dlls:

[DllImport("msvc r71.dll")]
static extern int _kbhit();

[DllImport("msvc r71.dll")]
static extern char _getwch();

// return true/false if a keypress is pending
public static bool KeyPressed
{
get
{
return (_kbhit() != 0);
}
}

// fetch next char in buffer else null - return immediately
public static char GetChar()
{
return (KeyPressed) ? _getwch() : NullChar;
}

// flush all pending keystrokes in buffer - return immediately
public static void FlushKeyboardBu ffer()
{
while (KeyPressed) GetChar();
}

Nov 17 '05 #2
Thanks for the super-speedy response, unfortunately, it didn't work,
the keyup event still fired. Here's my code:

public class KillKeysFilter : System.Windows. Forms.Form,IMes sageFilter
{
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
public bool PreFilterMessag e(ref Message m)
{
Keys keyCode = (Keys)(int)m.WP aram & Keys.KeyCode;
if (
(m.Msg == WM_KEYUP && keyCode == Keys.Enter) ||
(m.Msg == WM_KEYUP && keyCode == Keys.Tab) ||
(m.Msg == WM_KEYDOWN && keyCode == Keys.Enter) ||
(m.Msg == WM_KEYDOWN && keyCode == Keys.Tab)
)
{
return true;
}
return false;
}
}
public class MessageBox
{

/*
///// Method 1, PeekMessage
struct MSG
{
IntPtr hwnd;
uint message;
IntPtr wParam;
IntPtr lParam;
int time;
int ptX;
int ptY;
}
[DllImport("user 32.dll")]
static extern bool PeekMessage(out MSG lpMsg, uint hWnd, uint
wMsgFilterMin,u int wMsgFilterMax, uint wRemoveMsg);
const int PM_REMOVE = 0x0001;
const int WM_KEYFIRST = 0x0100;
const int WM_KEYLAST = 0x0109;
private static void KillKeysStart()
{
}
private static void KillKeysEnd()
{
MSG Msg;
while(PeekMessa ge(out Msg, 0, WM_KEYFIRST, WM_KEYLAST,PM_R EMOVE ))
;
}
*/

/*
// Method 2, MessageFilter
private static KillKeysFilter kkf=new KillKeysFilter( );
private static void KillKeysStart()
{
Application.Add MessageFilter(k kf);
Application.DoE vents();
}
private static void KillKeysEnd()
{
Application.DoE vents();
Application.Rem oveMessageFilte r(kkf);
}
*/

// Method 3, kbhit/getwch
[DllImport("msvc r71.dll")]
static extern int _kbhit();
[DllImport("msvc r71.dll")]
static extern char _getwch();
// return true/false if a keypress is pending
public static bool KeyPressed
{
get { return (_kbhit() != 0); }
}
// flush all pending keystrokes in buffer - return immediately
public static void FlushKeyboardBu ffer()
{
while (KeyPressed) _getwch();
}
private static void KillKeysStart()
{
}
private static void KillKeysEnd()
{
FlushKeyboardBu ffer();
Application.DoE vents();
FlushKeyboardBu ffer();
}

public static DialogResult Show(string text)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(text);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(owner, text);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(text, caption);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(owner, text,
caption);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons) ;
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons, MessageBoxIcon icon)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons, icon);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon);

KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns button, MessageBoxIcon icon, MessageBoxDefau ltButton
defaultButton)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,button,i con,defaultButt on);

KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon,
MessageBoxDefau ltButton defaultButton)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon,defa ultButton);

KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons, MessageBoxIcon icon, MessageBoxDefau ltButton
defaultButton, MessageBoxOptio ns options)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons, icon,defaultBut ton,options);

KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon,
MessageBoxDefau ltButton defaultButton, MessageBoxOptio ns options)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon,defa ultButton,optio ns);

KillKeysEnd();
return(r);
}

}

Nov 17 '05 #3

The code didn't work or it did work and the issue now is the key up event??
Original post did not mention key up event issues...

If key up event is the issue then you might be in a spot. You'll either
have to set up a finite state machine such that you know when you are
flushing the keyboard {or some other mechanism to ignore event} else learn
enough about keyboard communications to PInvoke the chars out of the keyboard
buffer before windows sees them...

"nx*****@winvoi ce.com" wrote:
Thanks for the super-speedy response, unfortunately, it didn't work,
the keyup event still fired. Here's my code:

public class KillKeysFilter : System.Windows. Forms.Form,IMes sageFilter
{
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
public bool PreFilterMessag e(ref Message m)
{
Keys keyCode = (Keys)(int)m.WP aram & Keys.KeyCode;
if (
(m.Msg == WM_KEYUP && keyCode == Keys.Enter) ||
(m.Msg == WM_KEYUP && keyCode == Keys.Tab) ||
(m.Msg == WM_KEYDOWN && keyCode == Keys.Enter) ||
(m.Msg == WM_KEYDOWN && keyCode == Keys.Tab)
)
{
return true;
}
return false;
}
}
public class MessageBox
{

/*
///// Method 1, PeekMessage
struct MSG
{
IntPtr hwnd;
uint message;
IntPtr wParam;
IntPtr lParam;
int time;
int ptX;
int ptY;
}
[DllImport("user 32.dll")]
static extern bool PeekMessage(out MSG lpMsg, uint hWnd, uint
wMsgFilterMin,u int wMsgFilterMax, uint wRemoveMsg);
const int PM_REMOVE = 0x0001;
const int WM_KEYFIRST = 0x0100;
const int WM_KEYLAST = 0x0109;
private static void KillKeysStart()
{
}
private static void KillKeysEnd()
{
MSG Msg;
while(PeekMessa ge(out Msg, 0, WM_KEYFIRST, WM_KEYLAST,PM_R EMOVE ))
;
}
*/

/*
// Method 2, MessageFilter
private static KillKeysFilter kkf=new KillKeysFilter( );
private static void KillKeysStart()
{
Application.Add MessageFilter(k kf);
Application.DoE vents();
}
private static void KillKeysEnd()
{
Application.DoE vents();
Application.Rem oveMessageFilte r(kkf);
}
*/

// Method 3, kbhit/getwch
[DllImport("msvc r71.dll")]
static extern int _kbhit();
[DllImport("msvc r71.dll")]
static extern char _getwch();
// return true/false if a keypress is pending
public static bool KeyPressed
{
get { return (_kbhit() != 0); }
}
// flush all pending keystrokes in buffer - return immediately
public static void FlushKeyboardBu ffer()
{
while (KeyPressed) _getwch();
}
private static void KillKeysStart()
{
}
private static void KillKeysEnd()
{
FlushKeyboardBu ffer();
Application.DoE vents();
FlushKeyboardBu ffer();
}

public static DialogResult Show(string text)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(text);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(owner, text);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(text, caption);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption)
{
KillKeysStart() ;
DialogResult r=System.Window s.Forms.Message Box.Show(owner, text,
caption);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons) ;
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons);
KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons, MessageBoxIcon icon)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons, icon);
KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon);

KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns button, MessageBoxIcon icon, MessageBoxDefau ltButton
defaultButton)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,button,i con,defaultButt on);

KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon,
MessageBoxDefau ltButton defaultButton)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon,defa ultButton);

KillKeysEnd();
return(r);
}
public static DialogResult Show(string text, string caption,
MessageBoxButto ns buttons, MessageBoxIcon icon, MessageBoxDefau ltButton
defaultButton, MessageBoxOptio ns options)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(text,c aption,buttons, icon,defaultBut ton,options);

KillKeysEnd();
return(r);
}
public static DialogResult Show(IWin32Wind ow owner, string text,
string caption, MessageBoxButto ns buttons, MessageBoxIcon icon,
MessageBoxDefau ltButton defaultButton, MessageBoxOptio ns options)
{
KillKeysStart() ;
DialogResult
r=System.Window s.Forms.Message Box.Show(owner, text,caption,bu ttons,icon,defa ultButton,optio ns);

KillKeysEnd();
return(r);
}

}

Nov 17 '05 #4
The issue is that when I fire a MessageBox.Show () in my code, if the
user presses Enter or Esc to dismiss the MessageBox, the form
underneath gets a KeyUp event with that enter or esc key. I was trying
to create a wrapper around the standard MessageBox class that would
clear any keys from the buffer. So far, I've tried an IMessageFilter,
PeekMessage, and now kbhit/getwch. No matter what, anywhere I've got
MessageBox.Show (), that form is going to get those enter keys, which
are used for navigation(Send Keys(Keys.Tab) on enter). So if I pop up a
messagebox and tell the user they have an error someplace and then set
the focus to that textbox, the focus actually changes to the next
control in the tab order.

Let's say we have three controls..two textboxes and a button
TextBox1
TextBox2
Button1

I set the user on TextBox1, the user types in a number, presses enter,
the form changes their focus to TextBox2, they type in another number,
press enter, they are now on Button1, they press enter again and our
Button1 click event occurs. In this event, I decide there's something
wrong with TextBox1, give them a long winded description in the
MessageBox and send them back
to TextBox1 like this:
if(SomethingWro ngWithTextBox1)
{
MessageBox.Show ("Long winded") ;
Control1.Focus( );
return;
}

If the user click Ok to dismiss the messagebox, or pressed the space
bar, the user is then sitting on Control1, as expected.

If the user presses Enter, the user is sitting on Control2. The reason
why is that, apparently, by design,if the user presses enter or esc in
the messagebox, it keeps that key in buffer for whatever fired the
messagebox.

So I figured that if I could clear the keyboard buffer after the
MessageBox.Show (), I wouldn't get the focusing problem.

Nov 17 '05 #5
Ron
Your problem is not the MessageBox button but the Textbox's KeyUp event. The
focus changes on KeyDown (from the MessageBox), so when you release the key
you are already on the textbox, and therefore the KeyUp event for the textbox
fires and changes focus to the other textbox. If you do your focus changes on
KeyDown instead, you will not have that problem.

"nx*****@winvoi ce.com" wrote:
The issue is that when I fire a MessageBox.Show () in my code, if the
user presses Enter or Esc to dismiss the MessageBox, the form
underneath gets a KeyUp event with that enter or esc key. I was trying
to create a wrapper around the standard MessageBox class that would
clear any keys from the buffer. So far, I've tried an IMessageFilter,
PeekMessage, and now kbhit/getwch. No matter what, anywhere I've got
MessageBox.Show (), that form is going to get those enter keys, which
are used for navigation(Send Keys(Keys.Tab) on enter). So if I pop up a
messagebox and tell the user they have an error someplace and then set
the focus to that textbox, the focus actually changes to the next
control in the tab order.

Let's say we have three controls..two textboxes and a button
TextBox1
TextBox2
Button1

I set the user on TextBox1, the user types in a number, presses enter,
the form changes their focus to TextBox2, they type in another number,
press enter, they are now on Button1, they press enter again and our
Button1 click event occurs. In this event, I decide there's something
wrong with TextBox1, give them a long winded description in the
MessageBox and send them back
to TextBox1 like this:
if(SomethingWro ngWithTextBox1)
{
MessageBox.Show ("Long winded") ;
Control1.Focus( );
return;
}

If the user click Ok to dismiss the messagebox, or pressed the space
bar, the user is then sitting on Control1, as expected.

If the user presses Enter, the user is sitting on Control2. The reason
why is that, apparently, by design,if the user presses enter or esc in
the messagebox, it keeps that key in buffer for whatever fired the
messagebox.

So I figured that if I could clear the keyboard buffer after the
MessageBox.Show (), I wouldn't get the focusing problem.

Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
7697
by: herrcho | last post by:
What's the difference between STDIN and Keyboard buffer ? when i get char through scanf, i type in some characters and press enter, then, where do the characters go ? to STDIN or Keyboard buffer ? are they same ? thanks ^^
1
7191
by: Larry | last post by:
Hi my friends. How can I read keyboard buffer by C++ ? Best regards, Larry
2
18834
by: Don | last post by:
I've got a loop from within which I make a call to the API function GetAsyncKeystate to see if the Escape key was pressed. If it is, then the exit condition of the loop is met and the program goes on to display a simple messagebox. Unfortunately, the program seems to think the Escape key was meant for this messagebox, even though it appeared *after* the Escape key was pressed(!) and instantly closes the messagebox before you can even see...
0
6656
by: rs | last post by:
Hi guys, I am trying to read from a USB keyboard using vb.net and HID classes. the USB keyboard is not my primary keyboard. I have a ps2 keyboard connected and is detected in device manager as my keyboard. the USB keyboard is detected as HID keyboard device. the program finds the keyboard if it is attached. and I am getting valid handles. however, everytime I use the readfile function I am getting "object reference not set to an instant...
2
8749
by: rs | last post by:
Hi guys, I am trying to read from a USB keyboard using vb.net and HID classes. the USB keyboard is not my primary keyboard. I have a ps2 keyboard connected and is detected in device manager as my keyboard. the USB keyboard is detected as HID keyboard device. the program finds the keyboard if it is attached. and I am getting valid handles. however, everytime I use the readfile function I am getting "object reference not set to an instant...
2
9585
by: Mike | last post by:
Does anyone have a simple function to clear the keyboard buffer? I need to make sure and clear any keystrokes before I exit my application. Thanks, Mike
1
4595
by: Damir | last post by:
Hallo everybody Does anyone knows how to access Keyboard buffer? At the moment I'm catching KeyDown event of the form, and waiting for carrige return or return key, but sometimes the Keyboard scanner doesn't send those keys, so I would like to wait so long until keyboard buffer is empty. Any helb will be appriciated
3
5224
by: muthursyamburi | last post by:
Hello All, I'm really looking for a help in reading/writing the keyboard buffer in AIX (IBM Unix). In DOS, there is some memory addres (I remember it as 0x417) from where the keyboard buffer starts. But I need the same in AIX. My requirement is this. In AIX, we need to change the password every 60 days or so. And while changing, it wont accept the previous 4 passwords we used. But when you change to a new one, its difficult to remember the...
3
2995
by: NaN | last post by:
I've been trying to use _kbhit() but it didn't do what I thought it would from books, "Detects whether a keypress is available for reading." Herbert Schildt says, "If the user has pressed a key, this function returns true(non-0), but does not read the character. If no keystroke is pending, kbhit() returns false (0)." Here is the test code,
0
7927
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8220
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8352
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
5723
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5396
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2367
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1457
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1194
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.