我正在尝试使用JNA从java运行ShellExecute函数。我在非unicode文件夹上运行ShellExecuteA没有任何问题
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteA(WinDef.HWND hwnd,
String lpOperation,
String lpFile,
String lpParameters,
String lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
WString st = new WString("D:");
Shell32.INSTANCE.ShellExecuteA(h, "open", st.toString(), null, null, 1);
}
}
但是因为我希望能够在unicode文件夹上使用它,我实际上想要运行ShellExecuteW而不是A版本,但是无法想象如何。每次我运行以下代码时,它只是完成执行而不做任何事情或显示任何错误。
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteW(WinDef.HWND hwnd,
String lpOperation,
WString lpFile,
String lpParameters,
String lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
WString st = new WString("D:\\日本語");
Shell32.INSTANCE.ShellExecuteW(h, "open", st, null, null, 1);
}
}
我猜问题在于第三个参数spFile - 我尝试使用String,WString都一样。任何帮助将不胜感激。
谢谢。
因为这是答案,我在这里重复@ technomage对这个问题的评论:
如果您要明确使用宽字符串,通常需要将它们用于所有函数参数。对于所有C字符串,w32 API通常都有LPTCSTR,这意味着ascii的字符串和unicode的WString。
因此,工作代码是:
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteW(WinDef.HWND hwnd,
WString lpOperation,
WString lpFile,
WString lpParameters,
WString lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
WString file = new WString("D:\\日本語");
Shell32.INSTANCE.ShellExecuteW(h, new WString("open"), file, null, null, 1);
}
}