sono finalmente riuscito a risolvere il problema :) E ho trovato la seguente soluzione:
Prima estendere l'interfaccia User32 nel seguente modo
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);
}
quindi estendere l'interfaccia winuser con il codice di Windows Messaggio di cui hai bisogno, nel mio caso questo è il WM_DEVICECHANGE, perché voglio verificare se il dispositivo USB è stato collegato o scollegato dal computer.
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;
}
Quindi creare un'interfaccia con la funzione di richiamata, che sarà in realtà la mia funzione 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);
}
};
E poi da qualche parte nel codice del JFrame dove si inizializza cose aggiungere il nuovo indirizzo per la procedura di finestra con la funzione SetWindowLong:
// Get Handle to current window
HWND hWnd = new HWND();
hWnd.setPointer(Native.getWindowPointer(this));
MyUser32.MYINSTANCE.SetWindowLong(hWnd, MyUser32.GWLP_WNDPROC, listener);
Questo codice funziona bene, ma ho qualche dubbio riguardo una cosa Non sono sicuro che il valore restituito dalla funzione di callback sia corretto. Ho letto in MSDN che dopo aver gestito un messaggio WM_DEVICECHANGE la funzione di callback dovrebbe restituire true e non sono sicuro che il valore che sto attualmente restituendo sia quello atteso dal sistema, quindi qualsiasi suggerimento è benvenuto.
Se qualcuno è interessato a tutto il codice che ho scritto per la comunicazione HID basta chiedere, sarei più che felice di aiutarvi :)
Acclamazioni, Gabor.
Puoi inserire il codice che hai utilizzato. Grazie. –
Ho una domanda, non dovevi usare qualcosa come RegisterDeviceNotification o stai solo cercando dispositivi portuali per i quali Windows trasmette automaticamente WM_DEVICECHANGE? –