C#通过热键控制显示器开关的方法
本文实例讲述了c#通过热键控制显示器开关的方法。分享给大家供大家参考。
具体实现方法如下:
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
namespace openmonitor
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
hotkey.registerhotkey(this.handle, 100, 0, keys.f4);
hotkey.registerhotkey(this.handle,101,0,keys.f5);
}
class hotkey
{
// 如果函数执行成功,返回值不为0。
// 如果函数执行失败,返回值为0。要得到扩展错误信息,调用getlasterror。
[dllimport("user32.dll ", setlasterror = true)]
public static extern bool registerhotkey(
intptr hwnd, // 要定义热键的窗口的句柄
int id, // 定义热键id(不能与其它id重复)
keymodifiers fsmodifiers, // 标识热键是否在按alt、ctrl、shift、windows等键时才会生效
keys vk // 定义热键的内容
);
[dllimport("user32.dll ", setlasterror = true)]
public static extern bool unregisterhotkey(
intptr hwnd, // 要取消热键的窗口的句柄
int id // 要取消热键的id
);
// 定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
[flags()]
public enum keymodifiers
{
none = 0,
alt = 1,
ctrl = 2,
shift = 4,
windowskey = 8
}
}
protected override void wndproc(ref message m)
{
const int wm_hotkey = 0x0312;
// 按快捷键
switch (m.msg)
{
case wm_hotkey:
switch (m.wparam.toint32())
{
case 100:
monitorhelper.turnon();
break;
case 101:
monitorhelper.turnoff();
break;
}
break;
}
base.wndproc(ref m);
}
class monitorhelper
{
public static void turnon()
{
sendmessage(hwnd_broadcast, wm_syscommand, sc_monitorpower, -1);
}
public static void turnoff()
{
sendmessage(hwnd_broadcast, wm_syscommand, sc_monitorpower, 2);
}
[dllimport("user32.dll")]
public static extern int sendmessage(intptr hwnd, uint msg, int wparam, int lparam);
private static readonly intptr hwnd_broadcast = new intptr(0xffff);
private const uint wm_syscommand = 0x0112;
private const int sc_monitorpower = 0xf170;
}
}
}
希望本文所述对大家的c#程序设计有所帮助。