473,606 Members | 2,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem trying to trap key down event on WinForm....

If you create a new C# Windows Application project in Visual
Studio.NET 2003 or 2005 and proceed to.

1. Make default form size 800x600
2. Drop a CheckBoxList control and dock it to the left
3. Drop a webBrowser control and dock it to the top
4. Drop a panel control and dock it to fill

Make the web browser about 60% of the form height height and make the
panel control about 40% of the height.

5. Set the form properties so that KeyPreview is set to true.
6. Create an event handler for KeyDown on the form

In the KeyDown event handler do a MessageBox.Show () to show the key
value.

All that will take about 3 minutes to setup thanks to the wonder of
Visual Studio, now if you launch the app you'll notice on any key
press you get the expected key value.... Unless you happen to do a few
specific things.

Here are two test that anyone can perform to reproduce the problem
with the KeyDown event handler.

A. Close the app (if it's open) and relaunch it. Immediately when it
opens, before hitting any keys, proceed to single-click on the web
browser area of the form, then hit any key, you'll notice the event
apparently is not being fired or not being handled.

B. Close the app (if it's open) and relaunch it. Immediately when it
opens, before hitting any keys, proceed to mouse left-click many times
on the panel area (click 5 or 6 times rapidly) then hit any key on the
keyboard, the key press event handler no longer gets triggered. You
can proceed to click on any other portion of the win form and the
keydown handler will start working again, but if you rapidly click on
the panel area (5-10 left-clicks), the KeyDown event handler seemingly
randomly stops working.

Following these steps this problem is easy to reproduce for anyone.
I've done it now on three systems, for reference I'm using Visual
Studio.NET 2005

Jun 15 '07 #1
1 10899
I found a solution. You have to create a new class that implements the
IMessageFilter interface and then in Program.cs you have to add the
MessageFilter and then pass it to your Form class through the
constructor. Then you inside your Form constructor you have to create
an event handler to the KeyPressed event (see code below for how
KeyPressed is defined in KeyboardMsgFilt er). This solution is much
more reliable than setting KeyPreview = true and trapping on the
WinForms KeyPress or KeyDown events. The later approach has some
issues of my first post to this thread details.
public class KeyboardMsgFilt er : IMessageFilter
{
public delegate void KeyboardEvent(o bject source, string
keyVal);
public event KeyboardEvent KeyPressed;

public bool PreFilterMessag e(ref Message m)
{
string key = "";
const int WM_KEYDOWN = 0x0100;

if (m.Msg == WM_KEYDOWN)
{

int keycode = Convert.ToInt32 (m.LParam.ToStr ing());
switch (keycode)
{
case 1179649 :
key = "E";
break;
case 1245185 :
key = "R";
break;
case 2031617 :
key = "S";
break;

}

if (key != "")
{
KeyPressed(null , key);
}

}
return false;
}
}

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Ena bleVisualStyles ();
Application.Set CompatibleTextR enderingDefault (false);
KeyboardMsgFilt er kmf = new KeyboardMsgFilt er();
Application.Add MessageFilter(k mf);

Application.Run (new Form1(kmf));
}
}

Jun 15 '07 #2

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

Similar topics

2
3585
by: Anthony | last post by:
I am trying to get a users DN by translating the LOGON_USER NT4 format variable. I am ONLY using windows authentication for security settings: This is a Windows 2000 IIS 5 Server. Here is the .asp that I've stripped down.. feel free to paste the code for your own testing.. it works: ----------------- begin paste-- ----------- <% ' logon_user will be in DOMAIN\LANID format (NT4 Format) logonuser = Request.ServerVariables("LOGON_USER")
2
3277
by: Bob | last post by:
In a winform with a datagridview using cellvalidating event but also have a save button that is located on a tablebindignnavigator. The behaviour I observe is that if the cellvalidating issues a cancel = true after the save button has been clicked, the update statements in the click event of the save button still occur but nothing gets saved, which is OK. Except that I pop a message box in the click event after the update statements have...
0
1098
by: Event handle problem in C# | last post by:
Hello, may be some of you could help me. I have a winform with FormBorderStyle asigned to None (I need it in that way), and an AXWebBrowser with Dock asigned to Fill. My problem is that the MouseEnter event for the winform only work if I have a part of it visible, but in this case I must have the webbroser filling all the winform, so the event MouseEnter never work. And the webbrowser doen't have a MouseEnter event, so I can't call that...
1
2253
by: Jason Richmeier | last post by:
I am experiencing some unexpected behavior with the Form Load event in a Windows application. Hopefully, someone can explain why this behavior is occurring. In my application, I have a form that I would like to show multiple times throughout the life of the application. The startup code for this form can be quite lengthy so I am hiding and showning the form (versus unloading and loading it). If I show the form non-modally (using the...
7
3326
by: gel | last post by:
Below is how it is down with vbscript. What is the best way to convert this to python? strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery("select * from __instancecreationevent " _ & " within 1 where TargetInstance isa 'Win32_Process'")
2
3720
by: jyanmin.fang | last post by:
Hi, In my current project, I need to embed an .NET winform usercontrol in the aspx page (via <Objecttag). This winform usercontrol has an event called DoEvent (void DoEvent()). This winform usercontrol will fire this event upon certain action by the user. I tried to let the aspx page subscribe to this event via <script for="winObj1" event="DoEvent()" language="javascript"> window.alert("window control event happen!");
3
2431
prn
by: prn | last post by:
Hi folks, I've got something that's driving me crazy here. If you don't want to read a long explanation, this is not the post for you. My problematic Access app is a DB for keeping track of software test data. Each instance of a test is associated with a "test case", that is, a test item. Each test instance (or "run") may have a number of other characteristics too, such as browser used, OS (XP, Vista, Linux, Mac OSX, etc.), etc., but for...
1
1544
by: Chris Jobson | last post by:
>I have a canvas which I use for dragging shapes around such as rectangles Add Focusable="True" to the XAML for the PolyLine and Rectangle elements and then when you set the focus to them they will receive the KeyUp events. Chris Jobson
1
2630
by: karaballo | last post by:
Hi All, How to trap arrow key down event on MDIChild form? Form alone works fine without MDI container. I think, ToolStrip stole these arrows key down events. How I can redirect arrow key down events to my MDIForm.ActiveMdiChild?
0
7981
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8462
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
8127
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8320
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5470
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
3952
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2458
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
1574
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.