public static void executeAsAdmin(String command, String args) { SHELLEXECUTEINFO execInfo = new SHELLEXECUTEINFO(); execInfo.lpFile = new WString(command); if (args != null) { execInfo.lpParameters = new WString(args); } execInfo.nShow = Shell32X.SW_SHOWDEFAULT; execInfo.fMask = Shell32X.SEE_MASK_NOCLOSEPROCESS; execInfo.lpVerb = new WString("runas"); boolean result = Shell32X.INSTANCE.ShellExecuteEx(execInfo); if (!result) { int lastError = Kernel32.INSTANCE.GetLastError(); String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError); throw new RuntimeException("Error performing elevation: " + lastError + ": " + errorMessage + " (apperror=" + execInfo.hInstApp + ")"); } }
public static void main(String args[]) throws InterruptedException { Pointer pointer; System.out.println("running in " + System.getProperty("sun.arch.data.model")); System.out.println("Loading dll"); autoHotKeyDll lib = (autoHotKeyDll) Native.loadLibrary("AutoHotkey.dll", autoHotKeyDll.class); System.out.println("initialisation"); lib.ahktextdll(new WString(""), new WString(""), new WString("")); // Thread.sleep(100); // lib.addFile(new WString(System.getProperty("user.dir") + "\\lib.ahk"), 1); // Thread.sleep(1000); // System.out.println("function call"); // System.out.println("return:" + lib.ahkFunction(new WString("function"),new WString(""),new WString(""),new // WString(""),new WString(""),new WString(""),new WString(""),new WString(""),new WString(""),new // WString(""),new WString("")).getString(0)); Thread.sleep(1000); System.out.println("displaying cbBox"); lib.ahkExec(new WString("Send {Right}")); Thread.sleep(1000); }
public boolean changeWorkingDir(String name) { File f = new File(name); String dir; if (!f.exists() || !f.isDirectory()) { System.out.println("setWorkingDirectory failed. file not found " + name); return false; } else try { dir = f.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); return false; } boolean result = MyKernel32.INSTANCE.SetCurrentDirectoryW(new WString(dir)); if (result) System.setProperty("user.dir", dir); return result; }
private HWND createWindowsProcess() { WString windowClass = new WString(APPNAME); HMODULE hInst = libK.GetModuleHandle(""); WNDCLASSEX wndclass = new WNDCLASSEX(); wndclass.hInstance = hInst; wndclass.lpfnWndProc = SSHAgent.this; wndclass.lpszClassName = windowClass; // register window class libU.RegisterClassEx(wndclass); getLastError(); // create new window HWND winprocess = libU .CreateWindowEx( User32.WS_OVERLAPPED, windowClass, APPNAME, 0, 0, 0, 0, 0, null, // WM_DEVICECHANGE contradicts parent=WinUser.HWND_MESSAGE null, hInst, null); mutex = libK.CreateMutex(null, false, MUTEX_NAME); return winprocess; }
public synchronized MediaInfo open(File file) throws IOException, IllegalArgumentException { if (!file.isFile() || file.length() < 64 * 1024) { throw new IllegalArgumentException("Invalid media file: " + file); } String path = file.getCanonicalPath(); // on Mac files that contain accents cannot be opened via JNA WString file paths due to encoding differences so we use the buffer interface instead for these files if (Platform.isMac() && !StandardCharsets.US_ASCII.newEncoder().canEncode(path)) { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { if (openViaBuffer(raf)) { throw new IOException("Failed to initialize media info buffer: " + path); } } } if (0 == MediaInfoLibrary.INSTANCE.Open(handle, new WString(path))) { // failed to open file throw new IOException("Failed to open media file: " + path); } return this; }
/** * Extract media information for a particular file. * * @param filename name of the file * @return media information * @throws MediaInfoParseException if a parse error occurs */ public static MediaInfo mediaInfo(String filename) { MediaInfo result; LibMediaInfo lib = LibMediaInfo.INSTANCE; Pointer handle = lib.MediaInfo_New(); if (handle != null) { try { int opened = lib.MediaInfo_Open(handle, new WString(filename)); if (opened == 1) { WString data = lib.MediaInfo_Inform(handle); lib.MediaInfo_Close(handle); result = new Parser(data.toString()).parse(); } else { result = null; } } finally { lib.MediaInfo_Delete(handle); } } else { result = null; } return result; }
boolean findDevices() { WString pluginName = new WString("Saitek"); dol.DirectOutput_Initialize(pluginName); DirectOutputLibrary.HRESULT result = dol.DirectOutput_Enumerate((hDevice, pCtc) -> { devices.add(hDevice); }, null); for (Pointer p : devices) { Memory g = new Memory(16); DirectOutputLibrary.LPGUID guid = new DirectOutputLibrary.LPGUID(g.getPointer(0)); result = dol.DirectOutput_GetDeviceType(p, guid); String pseudoGuid = toGuidString(guid.getPointer().getByteArray(0, 16)); // the byte order isn't correct, but we don't care right now if (X52_PRO.equals(pseudoGuid)) { System.out.println("Found X52 Pro! Yay!"); x52pro = p; return true; } } return false; }
/** * Open. * * @param file * the file * @return true, if successful */ public boolean open(Path file) throws MediaInfoException { // create handle try { if (handle == null) { handle = MediaInfoLibrary.INSTANCE.New(); } } catch (LinkageError e) { return false; } if (file != null && isLoaded()) { return MediaInfoLibrary.INSTANCE.Open(handle, new WString(file.toAbsolutePath().toString())) > 0; } else { return false; } }
/** @see <a href="http://msdn.microsoft.com/en-us/library/aa380261(VS.85,printer).aspx">Reference</a> */ boolean CryptProtectData( CryptIntegerBlob pDataIn, WString szDataDescr, CryptIntegerBlob pOptionalEntropy, Pointer pvReserved, Pointer pPromptStruct, int dwFlags, CryptIntegerBlob pDataOut )/* throws LastErrorException*/;
/** @see <a href="http://msdn.microsoft.com/en-us/library/aa380882(VS.85,printer).aspx">Reference</a> */ boolean CryptUnprotectData( CryptIntegerBlob pDataIn, WString[] ppszDataDescr, CryptIntegerBlob pOptionalEntropy, Pointer pvReserved, Pointer pPromptStruct, int dwFlags, CryptIntegerBlob pDataOut )/* throws LastErrorException*/;
private ClusterGroupInfo getGroupNodeInfo(Pointer cluster, String groupName) { ClusterGroupInfo result = null; try { Pointer hGroup = Clusapi.INSTANCE.OpenClusterGroup(cluster, new WString(groupName)); if (hGroup == null) throw new RuntimeException( "Clusapi call to OpenClusterGroup returned err code " + MyKernel32.INSTANCE.GetLastError()); IntByReference lpcchNodeName = new IntByReference(); Memory lpszNodeName = new Memory(256); lpszNodeName.clear(); lpcchNodeName.setValue(256); int state = Clusapi.INSTANCE.GetClusterGroupState(hGroup, lpszNodeName, lpcchNodeName); String location = lpszNodeName.getString(0, true); if (state == Clusapi.CLUSTER_GROUP_STATE_UNKNOWN) _log.severe("unknown group state for group " + groupName + " err code " + MyKernel32.INSTANCE.GetLastError()); result = new ClusterGroupInfo(groupName, state, location); MyKernel32.INSTANCE.CloseHandle(hGroup); } catch (Exception e) { _log.log(Level.SEVERE, "Error while getting GroupActiveNode", e); } return result; }
@Override public void setString(long offset, WString value) { if (m_sealed) throw new UnsupportedOperationException(); super.setString(offset, value); }
public static String staticOption(String option, String value) { try { return MediaInfoLibrary.INSTANCE.Option(null, new WString(option), new WString(value)).toString(); } catch (LinkageError e) { throw new MediaInfoException(e); } }
public static List<Process> getProcessesUsing(File file) { List<Process> processes = new LinkedList<Process>(); // If the DLL was not present (XP or other OS), do not try to find it again. if (ourFailed) { return processes; } try { IntByReference session = new IntByReference(); char[] sessionKey = new char[Win32RestartManager.CCH_RM_SESSION_KEY + 1]; int error = Win32RestartManager.INSTANCE.RmStartSession(session, 0, sessionKey); if (error != 0) { Runner.logger.warn("Unable to start restart manager session"); return processes; } StringArray resources = new StringArray(new WString[]{new WString(file.toString())}); error = Win32RestartManager.INSTANCE.RmRegisterResources(session.getValue(), 1, resources, 0, Pointer.NULL, 0, null); if (error != 0) { Runner.logger.warn("Unable to register restart manager resource " + file.getAbsolutePath()); return processes; } IntByReference procInfoNeeded = new IntByReference(); Win32RestartManager.RmProcessInfo info = new Win32RestartManager.RmProcessInfo(); Win32RestartManager.RmProcessInfo[] infos = (Win32RestartManager.RmProcessInfo[])info.toArray(MAX_PROCESSES); IntByReference procInfo = new IntByReference(infos.length); error = Win32RestartManager.INSTANCE.RmGetList(session.getValue(), procInfoNeeded, procInfo, info, new LongByReference()); if (error != 0) { Runner.logger.warn("Unable to get the list of processes using " + file.getAbsolutePath()); return processes; } for (int i = 0; i < procInfo.getValue(); i++) { processes.add(new Process(infos[i].Process.dwProcessId, new String(infos[i].strAppName).trim())); } Win32RestartManager.INSTANCE.RmEndSession(session.getValue()); } catch (Throwable t) { // Best effort approach, if no DLL is found ignore. ourFailed = true; } return processes; }
public byte[] encode(File file) { byte[] path = new byte[file.getAbsolutePath().length() * 3 + 1]; int pathLength = libC.wcstombs(path, new WString(file.getAbsolutePath()), path.length); if (pathLength < 0) { throw new RuntimeException(String.format("Could not encode file path '%s'.", file.getAbsolutePath())); } byte[] zeroTerminatedByteArray = new byte[pathLength + 1]; System.arraycopy(path, 0, zeroTerminatedByteArray, 0, pathLength); zeroTerminatedByteArray[pathLength] = 0; return zeroTerminatedByteArray; }
@Override public String GetEnsembleName(long dabIndex, boolean shortname) { WString buffer = new WString(""); if (!monkeyBoard.GetEnsembleName(new NativeLong(dabIndex), (byte) (shortname ? 0 : 1), buffer)) return ""; return buffer.toString(); }
void updatePage() { executor.submit(() -> { int no = pages.indexOf(this); if (no == activePage) { for (int i = topLine, row = 0; row < 3; i++, row++) { WString line = new WString(i < lines.size() ? lines.get(i) : ""); DirectOutputLibrary.HRESULT result = dol.DirectOutput_SetString(x52pro, no, row, line.length(), line); //System.out.println("Result:" + result); } } }); }
/** * Static option. * * @param option * the option * @param value * the value * @return the string */ public static String staticOption(String option, String value) { try { return MediaInfoLibrary.INSTANCE.Option(null, new WString(option), new WString(value)).toString(); } catch (Error e) { // throw new MediaInfoException(e); LOGGER.error("Failed to load mediainfo", e); return ""; } }
public static void clipboardMonitor() { WString windowClass = new WString("MyWindowClass"); HMODULE hInst = Kernel32.INSTANCE.GetModuleHandle(""); WNDCLASSEX wClass = new WNDCLASSEX(); wClass.hInstance = hInst; WindowProc wProc = new WindowProc(); wClass.lpfnWndProc = wProc; wClass.lpszClassName = windowClass; // register window class User32.INSTANCE.RegisterClassEx(wClass); getLastError(); // create new window HWND hWnd = User32.INSTANCE.CreateWindowEx(User32.WS_EX_TOPMOST, windowClass, "My hidden helper window, used only to catch the windows events", 0, 0, 0, 0, 0, null, null, hInst, null); getLastError(); // set clipboard viewer HWND nextViewer = User32X.INSTANCE.SetClipboardViewer(hWnd); wProc.setNextViewer(nextViewer); // pump messages MSG msg = new MSG(); while (User32.INSTANCE.GetMessage(msg, hWnd, 0, 0) != 0) { User32.INSTANCE.TranslateMessage(msg); User32.INSTANCE.DispatchMessage(msg); } // wait for input try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } // destroy window User32.INSTANCE.UnregisterClass(windowClass, hInst); User32.INSTANCE.DestroyWindow(hWnd); System.exit(0); }
boolean CreateProcessW(WString lpApplicationName, WString lpCommandLine, Structure lpProcessAttributes, Structure lpThreadAttributes, boolean bInheritHandles, int dwCreationFlags, Memory lpEnvironment, WString lpCurrentDirectory, Structure lpStartupInfo, Structure lpProcessInformation);
boolean CreateProcessWithLogonW(WString lpUsername, WString lpDomain, WString lpPassword, int dwLogonFlags, WString lpApplicationName, WString lpCommandLine, int dwCreationFlags, Memory lpEnvironment, WString lpCurrentDirectory, Structure lpStartupInfo, Structure lpProcessInfo);
boolean LogonUserW(WString lpszUsername, WString lpszDomain, WString lpszPassword, int dwLogonType, int dwLogonProvider, PointerByReference phToken);
boolean CreateProcessAsUserW(Pointer hToken, WString lpApplicationName, WString lpCommandLine, Structure lpProcessAttributes, Structure lpThreadAttributes, boolean bInheritHandles, int dwCreationFlags, Memory lpEnvironment, WString lpCurrentDirectory, Structure lpStartupInfo, Structure lpProcessInformation);
public synchronized String get(StreamKind streamKind, int streamNumber, String parameter, InfoKind infoKind, InfoKind searchKind) { return MediaInfoLibrary.INSTANCE.Get(handle, streamKind.ordinal(), streamNumber, new WString(parameter), infoKind.ordinal(), searchKind.ordinal()).toString(); }
/** * Start the KeyStore Explorer application. Takes one optional argument - * the location of a KeyStore file to open upon startup. * * @param args * the command line arguments */ public static void main(String args[]) { try { // To take affect these must be set before the splash screen is instantiated if (OperatingSystem.isMacOs()) { setAppleSystemProperties(); } else if (OperatingSystem.isWindows7() || OperatingSystem.isWindows8() || OperatingSystem.isWindows10()) { String appId = props.getString("KSE.AppUserModelId"); Shell32 shell32 = (Shell32) Native.loadLibrary("shell32", Shell32.class); shell32.SetCurrentProcessExplicitAppUserModelID(new WString(appId)).longValue(); } else if (OperatingSystem.isLinux()) { fixAppClassName(); } setInstallDirProperty(); SplashScreen splash = SplashScreen.getSplashScreen(); updateSplashMessage(splash, res.getString("KSE.LoadingApplicationSettings.splash.message")); ApplicationSettings applicationSettings = ApplicationSettings.getInstance(); setCurrentDirectory(applicationSettings); updateSplashMessage(splash, res.getString("KSE.InitializingSecurity.splash.message")); initialiseSecurity(); // list of files to open after start List<File> parameterFiles = new ArrayList<File>(); for (String arg : args) { File parameterFile = new File(arg); if (parameterFile.exists()) { parameterFiles.add(parameterFile); } } // Create application GUI on the event handler thread updateSplashMessage(splash, res.getString("KSE.CreatingApplicationGui.splash.message")); SwingUtilities.invokeLater(new CreateApplicationGui(applicationSettings, splash, parameterFiles)); } catch (Throwable t) { DError dError = new DError(new JFrame(), t); dError.setLocationRelativeTo(null); dError.setVisible(true); System.exit(1); } }
public WStringPointer(WString value) { super(); this.value = value; }
public WStringPointer(String value) { super(); this.value = new WString(value); }
public int ControlGetPosWidth(String Title, String Text, String Control) { return lib().AU3_ControlGetPosWidth(new WString(Title), new WString(Text), new WString(Control)); }
public void MouseWheel(String Direction, int Clicks) { lib().AU3_MouseWheel(new WString(Direction), Clicks); }
public int ProcessWaitClose(String Process, int Timeout) { return lib().AU3_ProcessWaitClose(new WString(Process), Timeout); }
public int ProcessClose(String Process) { return lib().AU3_ProcessClose(new WString(Process)); }
public int WinGetPosY(String Title, String Text) { return lib().AU3_WinGetPosY(new WString(Title), new WString(Text)); }
public void Send(String key) { ReporterNGExt.logAction("", "", String.format("AutoIt - Send: key [%s]", key)); lib().AU3_Send(new WString(key), 0); Sleeper.sleepTight(200); }
public int WinClose(String Title, String Text) { return lib().AU3_WinClose(new WString(Title), new WString(Text)); }
public void DriveMapGet(String Device, byte[] Mapping, int BufSize) { lib().AU3_DriveMapGet(new WString(Device), Mapping, BufSize); }
public UAutoItX ControlSend(String Title, String Text, String Control, String SendText, int Mode) { ReporterNGExt.logAction("", "", String.format("AutoIt - ControlSend: Title [%s] Text [%s] Control [%s] SendText [%s] Mode [%d]", Title, Text, Control, SendText, Mode)); lib().AU3_ControlSend(new WString(Title), new WString(Text), new WString(Control), new WString(SendText), Mode); Sleeper.sleepTight(200); return this; }
@Declared("sys/sendpraat.c") public static WString sendpraatW (Object display, String programName, long timeOut, WString text) { return Praat.INSTANCE.sendpraatW(display, programName, new NativeLong(timeOut), text); }
public int WinWaitActive(String Title, String Text, int Timeout) { return lib().AU3_WinWaitActive(new WString(Title), new WString(Text), Timeout); }
public int RegDeleteKey(String Keyname) { return lib().AU3_RegDeleteKey(new WString(Keyname)); }
public int WinGetPosHeight(String Title, String Text) { return lib().AU3_WinGetPosHeight(new WString(Title), new WString(Text)); }