In a KeyDown event I used SuppressKeyPress to avoid calling KeyPress and KeyUp events. However, although the KeyPress event was stopped the KeyUp event still fires. Why is this?
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.H)
{
listBox1.Items.Add("key down" + e.KeyCode);
// e.SuppressKeyPress = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'h')
{
listBox1.Items.Add("key press" + e.KeyChar);
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.H)
{
listBox1.Items.Add("key up" + e.KeyCode);
}
}
Taking a look at how SuppressHeyPress is handled in Control class:
protected virtual bool ProcessKeyEventArgs(ref Message m)
{
// ...
if (e.SuppressKeyPress)
{
this.RemovePendingMessages(0x102, 0x102);
this.RemovePendingMessages(0x106, 0x106);
this.RemovePendingMessages(0x286, 0x286);
}
return e.Handled;
}
it's obvious you can't do something like this to suppress a WM_KEYUP message (when a you process the KeyDown event, a KeyPress message is already sent to your control, but the KeyUp message won't fire until the user release the key).
You can test this with following code:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct MSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int pt_x;
public int pt_y;
}
private void RemovePendingMessages(Control c, int msgMin, int msgMax)
{
if (!this.IsDisposed)
{
MSG msg = new MSG();
IntPtr handle = c.Handle;
while (PeekMessage(ref msg, new HandleRef(c, handle), msgMin, msgMax, 1))
{
}
}
}
private void SuppressKeyPress(Control c)
{
this.RemovePendingMessages(c, 0x102, 0x102);
this.RemovePendingMessages(c, 0x106, 0x106);
this.RemovePendingMessages(c, 0x286, 0x286);
}
private void SuppressKeyUp(Control c)
{
this.RemovePendingMessages(c, 0x101, 0x101);
this.RemovePendingMessages(c, 0x105, 0x105);
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.H)
{
SuppressKeyPress(sender); // will work
SuppressKeyUp(sender); // won't work
}
}
A solution would be to use a boolean flag suppressKeyUp, set it to true at KeyDown and check it and resetting it in KeyUp, but you'll have to check it thoroughly and see what happens when the user misbehaves (like pressing two keys).
Yeah, try putting
e.Handled = true;
after the e.Suppress... = true;.
Related
I want to send message to other process already running. What wrong...? why I am not able to receive messages
My sender code is as below
public partial class RegisterWindowMessage : Form
{
[DllImport("User32.dll", EntryPoint = "SendMessage")]
//private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
private static extern int SendMessage(IntPtr hWnd, int Msg, string s, int i);
const int WM_SETTEXT = 0X000C;
public RegisterWindowMessage()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Process[] procs = Process.GetProcesses();
foreach (Process p in procs)
{
if (p.ProcessName.Equals("TaskScheduling"))
{
IntPtr hWnd = p.MainWindowHandle;
Thread.Sleep(1000);
SendMessage(hWnd, WM_SETTEXT, "This is the new Text!!!", 0);
MessageBox.Show("Inside");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
}
My receiver code is
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void frmReceiver_KeyDown(object sender, KeyEventArgs e)
{
// this.lsvMsgList.Items.Add(e.KeyValue.ToString());
}
protected override void WndProc(ref Message m)
{
MessageBox.Show(m.Msg.ToString());
MessageBox.Show(m.LParam.ToString());
MessageBox.Show(m.WParam.ToString());
if (m.LParam.ToInt32() == 1)
{
}
else
{
base.WndProc(ref m);
}
}
}
I want to know why i am not able to receive message. Let me know where I am wrong
I'm currently trying to set a single key as global hook. Howerver, I was perhaps wondering if it's possible to manipulate this code, so that a single button is set as a global hot key?
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
const int B = 0x42;
const int MOD_SHIFT = 0x0004;
const int WM_HOTKEY = 0x0312;
private void Form1_Load(object sender, EventArgs e)
{
RegisterHotKey(this.Handle, 1, B + MOD_SHIFT, (int)Keys.X);
RegisterHotKey(this.Handle, 2, B + MOD_SHIFT, (int)Keys.Y);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 1);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY && (int)m.WParam == 1)
MessageBox.Show("Hotkey X pressed.");
if (m.Msg == WM_HOTKEY && (int)m.WParam == 2)
MessageBox.Show("Hotkey Y pressed.");
base.WndProc(ref m);
}
}
}
I'm programming kind of security application
it records the keyboard keys ..
i want to hide the application and then show it when the user presses a key
i tried the following
Hide Button :
private void button4_Click(object sender, EventArgs e)
{
ShowInTaskbar = false;
this.Visible = false;
this.TopMost = true;
}
and key event
private void KeyEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Control && e.Modifiers== Keys.F12) {
this.Visible = true;
}
}
and of course the form load
private void Form2_Load(object sender, EventArgs e)
{
KeyPreview = true;
this.KeyUp+=new System.Windows.Forms.KeyEventHandler(KeyEvent);
}
But no matter how many times i press the keys .. i wont show !!
What should i do ??
As others have stated, your app won't have input focus and won't be listening to key presses.
You need to hook into RegisterHotKey in user32.dll, e.g:
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
Example:
public class GlobalHotKey
{
private int modifier;
private int key;
private IntPtr hWnd;
private int id;
public GlobalHotKey(int modifier, Keys key, Form form)
{
this.modifier = modifier;
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}
public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
public override int GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
public static class Constants
{
public const int NOMOD = 0x0000;
public const int ALT = 0x0001;
public const int CTRL = 0x0002;
public const int SHIFT = 0x0004;
public const int WIN = 0x0008;
public const int WM_HOTKEY_MSG_ID = 0x0312;
}
Usage:
private GlobalHotKey globalHotKey;
// Registering your hotkeys
private void Form2_Load(object sender, EventArgs e)
{
globalHotKey = new HotKeys.GlobalHotKey(Constants.CTRL, Keys.F12, this);
bool registered = globalHotKey.Register();
// Handle instances where the hotkey failed to register
if(!registered)
{
MessageBox.Show("Hotkey failed to register");
}
}
// Listen for messages matching your hotkeys
protected override void WndProc(ref Message m)
{
if (m.Msg == HotKeys.Constants.WM_HOTKEY_MSG_ID)
{
HandleHotkey();
}
base.WndProc(ref m);
}
// Do something when the hotkey is pressed
private void HandleHotkey()
{
if(this.Visible)
this.Hide();
else
this.Show();
}
You'll want to make sure you unregister the key when the app closes too:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!globalHotKey.Unregister())
{
Application.Exit();
}
}
This is because your application does not have input focus and therefore will not be picking up the key presses. You need to hook into lower-level OS to get keyboard input when your application does not have focus.
A similar question was posted and answered here: Global keyboard capture in C# application
Read documentation? Aan application only gets the key presses for its windows. Logically this means a hidden window can not get key presses.
You hook into the forms handler so you only see the presses on your forms, which are invisible so never can have the focus to get key presses.
There are HOOKS you can use in Windows to hook into the general processing, but beare side effects (i.e. other programs also reacting or you blocking keys).
I suggest looking into this:
Processing global mouse and keyboard hooks from C#
In essense, what you want lies outside of .net capabilities, and must be implemented via Windows API, and, consequently, using a native language. However when you recieve input through winAPI, you can pass it to your application, using project i linked to as a guide.
I been searching around for a solution for my problem but for now I wasn't able to get any sucessfull code for what I want to do. So, I have a form without border that is filled with 2 custom panels, so there is no way to the user click on the frame, thinking in that, I implement a code that when user click on a panel, this will call a function on my form that recive by parameter the event of the mouse.
This is the code of my Panel (note that both of my panels in the frame are the same class, it's just 2 diferent instances)
public class MyPanel : System.Windows.Forms.Panel{
(...)
private void MyPanel_MouseDown(object sender, MouseEventArgs e)
{
BarraSms.getInstance().mouseDown(e);
}
private void MyPanel_MouseMove(object sender, MouseEventArgs e)
{
BarraSms.getInstance().mouseMove(e);
}
}
And this is the code of my form:
public partial class BarraSms : Form
{
private Point mousePoint;
(...)
public void mouseDown(MouseEventArgs e) {
mousePoint = new Point(-e.X, -e.Y);
}
public void mouseMove(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mousePoint .X, mousePoint .Y);
this.Location = mousePos;
}
}
}
Is there something that I'm missing?
Thank you in advance for the help.
The working code (update), problem solved by: x4rf41
The MyPanel Class :
MouseMove += MyPanel_MouseMove; // added in class constructer
the BarraSms class (Form)
public partial class BarraSms : Form
{
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
public void mouseMove(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN, new IntPtr(HT_CAPTION), IntPtr.Zero);
Point loc = this.Location;
writeCoordToBin(loc.X, loc.Y);
}
}
}
There is much better solution for that using the windows api function.
The way you use it, you will have a problem when you move the form very fast and the mouse goes out of the panel. I had the exact same problem.
try this:
using System.Runtime.InteropServices;
and in your Form class
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
public void mouseMove(MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN, new IntPtr(HT_CAPTION), IntPtr.Zero);
}
}
no need for a mouseDown event for this
Your private methods in MyPanel cannot be called by the framework. You need to declare them as follows:
protected override void OnMouseDown(MouseEventArgs e)
{
var parent = this.Parent as BarraSms;
parent.mouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
var parent = this.Parent as BarraSms;
parent.mouseMove(e);
}
Try this:
public void mouseMove(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Point currentPos = Location;
currentPos.Offset(e.X + mousePoint.X, e.Y + mousePoint.Y);
this.Location = currentPos;
}
//Or simply use Location.Offset(e.X + mousePoint.X, e.Y + mousePoint.Y);
}
You have to use Location (the current location of the form), not the Control.MousePosition which is the location of mouse on screen.
UPDATE: Looks like you don't even know how to register event handlers, try modifying your panel class like this:
public class MyPanel : System.Windows.Forms.Panel{
//(...)
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
BarraSms.getInstance().mouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
BarraSms.getInstance().mouseMove(e);
}
}
I'm working on a program, who need to detect when the user press the keyboard or use his mouse, even if the program is minimized or not focused.
I think I have to use the windows API, keybd_event (user32), but I don't know how to use the "listener" of this event. I have something like that:
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
void PressKey(byte keyCode)
{
//My code here
}
I did some research, but it's the first time I have to use DllImport, so I don't know how to continue ...
Thanks
(Ps:Sorry about my bad English, this is not my native language :) )
(PPs: I've read all of your answers, but it takes a while to read every link, so I'll work on it tonight, but I think I will find the answer. Anyway, thanks for the links everybody ;) )
Edit: So I just finished my code and it's work :) It looks something like:
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
private void timerTemps_Inactif_Tick(object sender, EventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
if (IdleTime > 10000)
{
//My code here
}
}
}
Thanks for the help guys ;)
You will need to hook into Windows OS with SetWindowsHookEx function. You should read the article Keyloggers: How they work and how to detect them posted by SecureList to get a understanding ofthe process.
I have always got a good performance by using RegisterHotKey/UnregisterHotKey functions. Sample code:
[DllImport("User32")]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
int fsModifiers,
int vk
);
[DllImport("User32")]
public static extern bool UnregisterHotKey(
IntPtr hWnd,
int id
);
public const int MOD_SHIFT = 0x4;
public const int MOD_CONTROL = 0x2;
public const int MOD_ALT = 0x1;
public const int WM_HOTKEY = 0x312;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY && m.WParam == (IntPtr)0)
{
IntPtr lParamCTRLA = (IntPtr)4259842;
IntPtr lParamB = (IntPtr)4325376;
if (m.LParam == lParamCTRLA)
{
MessageBox.Show("CTRL+A was pressed");
}
else if (m.LParam == lParamB)
{
MessageBox.Show("B was pressed");
}
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
RegisterHotKey(this.Handle, 0, MOD_CONTROL, (int)Keys.A);
RegisterHotKey(this.Handle, 0, 0, (int)Keys.B);
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0);
}
You can "register" as many keys (or combination of keys) as you want by emulating the shown structure. All the registered keys will get inside the condition if (m.Msg == WM_HOTKEY && m.WParam == (IntPtr)0); if they are pressed at all (independently upon the program currently being selected). The easiest way to know the specific key/combination being pressed is relying on m.LParam (I got the two values I am including after a quick test with the given keys). You can do a quick research to find out a list of LParam or further constant modifiers (wheel of the mouse, for example).
The final code:
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
private void timerTemps_Inactif_Tick(object sender, EventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
if (IdleTime > 10000)
{
//My code here
}
}
}