|
|
发表于 2005-8-19 12:56:00
|
显示全部楼层
Re:如何用directinput捕捉鼠标事件
关于鼠标操作(MDX9 C#)
首先需要引用
using Microsoft.DirectX.DirectInput;命名空间
准备变量
private Device m_deviceMouse = null;
1、初始化设备
//取得设备句柄
m_deviceMouse = new Device(SystemGuid.Mouse);
//设置数据类型
m_deviceMouse.SetDataFormat(DeviceDataFormat.Mouse);
//协作级别
m_deviceMouse.SetCooperativeLevel(parentWindowControl,
CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.NonExclusive);
/*
CooperativeLevelFlags
Background
The device can be used in the background, and can be acquired at any time, even if the associated window isn't the active window.
Foreground
The device can only be used if the window is in the foreground. When this window loses focus, any acquired device will be unacquired.
注意此种模式下,如果主窗口失去焦点则需要重新获得设备
Exclusive
The device requires exclusive access. While acquired exclusively, no other application can acquire the device exclusively. Nonexclusive acquires are still allowed. For security reasons, exclusive and background flags are not allowed to be used together on certain devices, like keyboards and mice.
NonExclusive
The device can be shared among many applications and does not require exclusive access.
NoWindowsKey
Disables the windows key.
*/
//设置坐标显示模式
this.m_deviceMouse.Properties.AxisModeAbsolute = true;
//取得设备
m_deviceMouse.Acquire();
2、关于坐标的说明
坐标分成X,Y,Z轴,X,Y对应屏幕的横轴和纵轴,Z对应鼠标滚轮。
X轴和Y轴的精度如果不设置AxisModeAbsolute的时候是很粗(具体多少我没测算),但是设置了AxisModeAbsolute之后是基本和屏幕象素一致。
Z轴的精度是120,也就是说鼠标滚轮向前滚一下则数值增加120,否则减少120。
从鼠标状态 m_deviceMouse.CurrentMouseState;得到的X,Y值不能明确指出当前鼠标在屏幕上的位置,如果需要得到屏幕鼠标位置,则需要使用Cursor.Position属性即可。
3、鼠标按钮
鼠标按钮在DXI中没有明确定义,需要自己定义。MouseState的GetMouseButtons方法取得鼠标的数组,按钮使用数组实现。
4、事件机制
普通模式取得鼠标状态在程序的主循环中使用轮询机制取得,但是MS提供了线程方式取得
实例代码如下
private void frmUI_Load(object sender, System.EventArgs e)
{
threadData = new Thread(new ThreadStart(this.MouseEvent));
threadData.Start();
eventFire = new AutoResetEvent(false);
// Create the device.
try
{
applicationDevice = new Device(SystemGuid.Mouse);
}
catch(InputException)
{
MessageBox.Show("Unable to create device. Sample will now exit.");
Close();
}
// Set the cooperative level for the device.
applicationDevice.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Foreground);
// Set a notification event.
applicationDevice.SetEventNotification(eventFire);
// Acquire the device.
try{ applicationDevice.Acquire(); }
catch{}
}
public void MouseEvent()
{
// This is the mouse event thread.
// This thread will wait until a
// mouse event occurrs, and invoke
// the delegate on the main thread to
// grab the current mouse state and update
// the UI.
while(Created)
{
eventFire.WaitOne(-1, false);
try
{
applicationDevice.Poll();
}
catch(InputException)
{
continue;
}
this.BeginInvoke(new UIDelegate(UpdateUI));
}
}
public void UpdateUI()
{
MouseState mouseStateData = new MouseState();
// Get the current state of the mouse device.
mouseStateData = applicationDevice.CurrentMouseState;
byte[] buttons = mouseStateData.GetMouseButtons();
}
|
|