我终于设法解决了这个问题:) 我找到了以下解决方案:
首先通过如下方式扩展User32接口
public interface MyUser32 extends User32 {
public static final MyUser32 MYINSTANCE = (MyUser32) Native.loadLibrary("user32", MyUser32.class, W32APIOptions.UNICODE_OPTIONS);
/**
* Sets a new address for the window procedure (value to be set).
*/
public static final int GWLP_WNDPROC = -4;
/**
* Changes an attribute of the specified window
* @param hWnd A handle to the window
* @param nIndex The zero-based offset to the value to be set.
* @param callback The callback function for the value to be set.
*/
public int SetWindowLong(WinDef.HWND hWnd, int nIndex, Callback callback);
}
然后使用您需要的 Windows 消息代码扩展 WinUser 界面,在我的情况下,这是 WM_DEVICECHANGE,因为我想检查 USB 设备是否已与计算机连接或分离。
public interface MyWinUser extends WinUser {
/**
* Notifies an application of a change to the hardware configuration of a device or the computer.
*/
public static final int WM_DEVICECHANGE = 0x0219;
}
然后用回调函数创建一个接口,这实际上就是我的 WndProc 函数。
//Create the callback interface
public interface MyListener extends StdCallCallback {
public LRESULT callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam);
}
public MyListener listener = new MyListener()
{
public LRESULT callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam)
{
if (uMsg == MyWinUser.WM_DEVICECHANGE)
{
// TODO Check If my device was attached or detached
return new LRESULT(1);
}
return new LRESULT(0);
}
};
然后在您初始化事物的 JFrame 代码中的某处使用 SetWindowLong 函数添加窗口过程的新地址:
// Get Handle to current window
HWND hWnd = new HWND();
hWnd.setPointer(Native.getWindowPointer(this));
MyUser32.MYINSTANCE.SetWindowLong(hWnd, MyUser32.GWLP_WNDPROC, listener);
这段代码运行良好,但我对一件事有一些疑问。我不确定回调函数的返回值是否正确。我在 MSDN 中读到,在处理 WM_DEVICECHANGE 消息后,回调函数应该返回 true,我不确定我当前返回的值是否是系统预期的值,因此欢迎提出任何建议。
如果有人对我为 HID 通信编写的整个代码感兴趣,请询问,我将非常乐意提供帮助 :)
干杯,加博尔。