winform键盘事件问题

s136735431 2010-10-18 11:23:22


这个是窗体测试代码,请问需要添加什么代码才能实现在窗体没有获得焦点的情况下可以获得键盘输入。比如窗体隐藏了,在没有焦点的情况下按下N键能使窗体显示出来


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
this.Opacity = 0;
}
else if (e.KeyCode == Keys.Y)
{
this.Opacity = 1;
}
}

private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
}
}
}
...全文
206 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jieon 2010-10-29
  • 打赏
  • 举报
回复
RegisterHotKey(this.Handle, 1001,KeyModifiers.Control, Keys.S);
我设置,KeyModifiers.Control没有反应?,KeyModifiers.None才行
ZengHD 2010-10-19
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Management;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);

[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

private const int WM_HOTKEY = 0x0312;

[Flags()]
private enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}

private void Form1_Load(object sender, EventArgs e)
{
RegisterHotKey(this.Handle, 1001,KeyModifiers.Control, Keys.S);
RegisterHotKey(this.Handle, 1002, KeyModifiers.Control, Keys.C);
}

protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY)
{
if (m.WParam.ToInt32() == 1001)
{
MessageBox.Show("显示窗体");
}
else if (m.WParam.ToInt32() == 1002)
{
MessageBox.Show("关闭窗体");
}
return;
}

base.WndProc(ref m);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 1001);
UnregisterHotKey(this.Handle, 1002);
}
}

}
xuld 2010-10-19
  • 打赏
  • 举报
回复
键盘钩子

或在 Form 反应
feng442624978 2010-10-19
  • 打赏
  • 举报
回复
路过...本来想来解决的. 不过已经有人抢先了.
卓才琣 2010-10-19
  • 打赏
  • 举报
回复
注册热键就行了 4楼说得很明白
ZengHD 2010-10-18
  • 打赏
  • 举报
回复
RegisterHotKey啊
机器人 2010-10-18
  • 打赏
  • 举报
回复
高级点的系统消息拦截才行了。

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧