private void calc() { if (System.currentTimeMillis() - _lastCall < 500) return; WinBase.MEMORYSTATUSEX lpBuffer = new WinBase.MEMORYSTATUSEX(); lpBuffer.dwLength = new DWORD(lpBuffer.size()); if (Kernel32.INSTANCE.GlobalMemoryStatusEx(lpBuffer)) { lpBuffer.read(); _freeRAM = lpBuffer.ullAvailPhys.longValue(); _totalRAM = lpBuffer.ullTotalPhys.longValue(); _lastCall = System.currentTimeMillis(); } else { if (_logger != null) _logger.severe("ERROR: could not read free/total RAM"); else System.out.println("ERROR: could not read free/total RAM"); } }
private List<WinProcess> getChildren() throws IOException { ArrayList<WinProcess> result = new ArrayList<WinProcess>(); WinNT.HANDLE hSnap = this.kernel32lib.CreateToolhelp32Snapshot(Kernel32Lib.TH32CS_SNAPPROCESS, new DWORD(0)); Kernel32Lib.PROCESSENTRY32.ByReference ent = new Kernel32Lib.PROCESSENTRY32.ByReference(); if (!this.kernel32lib.Process32First(hSnap, ent)) { return result; } do { if (ent.th32ParentProcessID.intValue() == this.pid) { try { result.add(new WinProcess(ent.th32ProcessID.intValue())); } catch (IOException e) { System.err.println("WinProcess::getChildren, IOException " + e); } } } while (this.kernel32lib.Process32Next(hSnap, ent)); Kernel32.INSTANCE.CloseHandle(hSnap); return result; }
private static void setShutdownPrivileges() { final WinNT.HANDLEByReference token = new WinNT.HANDLEByReference(); Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES, token); final WinNT.LUID luid = new WinNT.LUID(); Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_SHUTDOWN_NAME, luid); final WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED)); Advapi32.INSTANCE.AdjustTokenPrivileges(token.getValue(), false, tp, 0, null, new IntByReference(0)); }
public void reboot() { setShutdownPrivileges(); if (!MyUser32.INSTANCE.ExitWindowsEx(new UINT(MyUser32.INSTANCE.EWX_REBOOT + MyUser32.INSTANCE.EWX_FORCE), new DWORD(MyUser32.INSTANCE.SHTDN_REASON_FLAG_PLANNED)).booleanValue()) { int err = MyKernel32.INSTANCE.GetLastError(); System.out.println("error executing reboot "+err+ " "+Kernel32Util.formatMessageFromLastErrorCode(err)); } }
/************************************************************************* * Parses the settings and creates an PAC ProxySelector for it. * * @param ieSettings * the IE settings to use. * @return a PacProxySelector the selector or null. ************************************************************************/ private PacProxySelector createPacSelector(IEProxyConfig ieProxyConfig) { String pacUrl = null; if (ieProxyConfig.isAutoDetect()) { Logger.log(getClass(), LogLevel.TRACE, "Autodetecting script URL."); // This will take some time. DWORD dwAutoDetectFlags = new DWORD( WinHttp.WINHTTP_AUTO_DETECT_TYPE_DHCP | WinHttp.WINHTTP_AUTO_DETECT_TYPE_DNS_A); pacUrl = WinHttpHelpers.detectAutoProxyConfigUrl(dwAutoDetectFlags); } if (pacUrl == null) { pacUrl = ieProxyConfig.getAutoConfigUrl(); } if (pacUrl != null && pacUrl.trim().length() > 0) { Logger.log(getClass(), LogLevel.TRACE, "IE uses script: " + pacUrl); // Fix for issue 9 // If the IE has a file URL and it only starts has 2 slashes, // add a third so it can be properly converted to the URL class if (pacUrl.startsWith("file://") && !pacUrl.startsWith("file:///")) { pacUrl = "file:///" + pacUrl.substring(7); } return ProxyUtil.buildPacSelectorForUrl(pacUrl); } return null; }
/** * Gets a list of currently active processes by creating a snapshot. * * @return List of currently active processes * @throws Win32Exception * If the operation was not successful */ public static ProcessList getProcessList() throws Win32Exception { final ProcessList plist = new ProcessList(); final List<PROCESSENTRY32> list = new LinkedList<>(); final HANDLE hProcessSnap = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new DWORD(0)); PROCESSENTRY32 pe32 = new PROCESSENTRY32(); if (!Kernel32.INSTANCE.Process32First(hProcessSnap, pe32)) { throw new Win32Exception(Native.getLastError()); } do { if (pe32.th32ProcessID.intValue() != 0) { list.add(pe32); } pe32 = new PROCESSENTRY32(); } while (Kernel32.INSTANCE.Process32Next(hProcessSnap, pe32)); for (final PROCESSENTRY32 pe : list) { plist.add(new Process(pe)); } Kernel32.INSTANCE.CloseHandle(hProcessSnap); final List<DesktopWindow> windows = WindowUtils.getAllWindows(false); final IntByReference lpdwProcessId = new IntByReference(); int pid = 0; for (final DesktopWindow window : windows) { User32.INSTANCE.GetWindowThreadProcessId(window.getHWND(), lpdwProcessId); pid = lpdwProcessId.getValue(); plist.add(pid, window.getHWND()); } return plist; }
public static void main(String argv[]) { String libraryName = "foo.jar"; System.load(libraryName); System.loadLibrary(libraryName); System.mapLibraryName(libraryName); Runtime.getRuntime().load(libraryName); Runtime.getRuntime().loadLibrary(libraryName); DWORD dword = new DWORD(0x12345678); Native.loadLibrary(MyLibrary.class); }
private void setVisible(boolean show) { if (show) { timer.schedule(new TimerTask() { public void run() { window.bringWindowToTop(); } }, 50); timer.schedule(new TimerTask() { INPUT input = null; public void run() { if (input == null) { int INPUT_MOUSE = 0; int MOUSEEVENTF_MOVE = 0x1; int MOUSEEVENTF_ABSOLUTE = 0x08000; int MOUSEEVENTF_LEFTDOWN = 0x2; int MOUSEEVENTF_LEFTUP = 0x4; input = new INPUT(); input.type = new DWORD(INPUT_MOUSE); // TODO get current position input.input.mi.dx = new LONG(config.x + 10); input.input.mi.dy = new LONG(config.y + 10); input.input.mi.dwFlags = new DWORD(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP); } // Put window on the top window.setForegroundWindow(); // Simulate click to set focus User32Ext.INSTANCE.SendInput(new UINT(1), input, input.size()); } }, 100); } else { timer.schedule(new TimerTask() { public void run() { window.showWindow(SW_HIDE); } }, 50); } isHidden = !show; }
public Win32Process(String filePath, String fileName, BufferedImage icon, DWORD th32ProcessID) { this.filePath = filePath; this.fileName = fileName; this.icon = icon; this.th32ProcessID = th32ProcessID; }
public PROCESSENTRY32() { dwSize = new WinDef.DWORD(size()); }
/** * Gets the list of processes on this machine. * * @return The list of processes on this machine. */ public static List<ProcessInfo> getProcessList() throws Exception { /* Initialize the empty process list. */ List<ProcessInfo> processList = new ArrayList<ProcessInfo>(); /* Create the process snapshot. */ HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot( Tlhelp32.TH32CS_SNAPPROCESS, new DWORD(0)); Tlhelp32.PROCESSENTRY32.ByReference pe = new Tlhelp32.PROCESSENTRY32.ByReference(); for (boolean more = Kernel32.INSTANCE.Process32First(snapshot, pe); more; more = Kernel32.INSTANCE.Process32Next(snapshot, pe)) { /* Open this process; ignore processes that we cannot open. */ HANDLE hProcess = Kernel32.INSTANCE.OpenProcess( 0x1000, /* PROCESS_QUERY_LIMITED_INFORMATION */ false, pe.th32ProcessID.intValue()); if (hProcess == null) { continue; } /* Get the image name. */ char[] imageNameChars = new char[1024]; IntByReference imageNameLen = new IntByReference(imageNameChars.length); if (!Kernel32.INSTANCE.QueryFullProcessImageName( hProcess, new DWORD(0), imageNameChars, imageNameLen)) { throw new Exception("Couldn't get process image name for " + pe.th32ProcessID.intValue()); } /* Add the process info to our list. */ processList.add(new ProcessInfo( pe.th32ProcessID.intValue(), pe.th32ParentProcessID.intValue(), new String(imageNameChars, 0, imageNameLen.getValue()))); /* Close the process handle. */ Kernel32.INSTANCE.CloseHandle(hProcess); } /* Close the process snapshot. */ Kernel32.INSTANCE.CloseHandle(snapshot); /* Return the process list. */ return processList; }
/** * Check if the if the security descriptor grants access to the given client token. * * @param pSecurityDescriptor [in] A pointer to a SECURITY_DESCRIPTOR structure against which access is checked. * @param ClientToken [in] A handle to an impersonation token that represents the client that is attempting to gain access. The handle must have TOKEN_QUERY access to the token; otherwise, the function fails with ERROR_ACCESS_DENIED. * @param DesiredAccess [in] Access mask that specifies the access rights to check. This mask must have been mapped by the MapGenericMask function to contain no generic access rights.<br> * If this parameter is MAXIMUM_ALLOWED, the function sets the GrantedAccess access mask to indicate the maximum access rights the security descriptor allows the client. * @param GenericMapping [in] A pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. * @param PrivilegeSet [out, optional] A pointer to a PRIVILEGE_SET structure that receives the privileges used to perform the access validation. If no privileges were used, the function sets the PrivilegeCount member to zero. * @param PrivilegeSetLength [in, out] Specifies the size, in bytes, of the buffer pointed to by the PrivilegeSet parameter. * @param GrantedAccess [out] A pointer to an access mask that receives the granted access rights. If AccessStatus is set to FALSE, the function sets the access mask to zero. If the function fails, it does not set the access mask. * @param AccessStatus [out] A pointer to a variable that receives the results of the access check. If the security descriptor allows the requested access rights to the client identified by the access token, AccessStatus is set to TRUE. Otherwise, AccessStatus is set to FALSE, and you can call GetLastError to get extended error information. * @return true on success; false on failure (use GetLastError to get extended error information) */ public boolean AccessCheck(Pointer pSecurityDescriptor, HANDLE ClientToken, DWORD DesiredAccess, GENERIC_MAPPING GenericMapping, PRIVILEGE_SET PrivilegeSet, DWORDByReference PrivilegeSetLength, DWORDByReference GrantedAccess, BOOLByReference AccessStatus);
/** * Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes. * * @param dwFlags The portions of the system to be included in the snapshot. * @param th32ProcessID The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate * the current process. This parameter is used when the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, * TH32CS_SNAPMODULE32, or TH32CS_SNAPALL value is specified. Otherwise, it is ignored and all processes are * included in the snapshot. * <p/> * If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last * error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them. * <p/> * If the specified process is a 64-bit process and the caller is a 32-bit process, this function fails and the * last error code is ERROR_PARTIAL_COPY (299). * @return If the function succeeds, it returns an open handle to the specified snapshot. * <p/> * If the function fails, it returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. * Possible error codes include ERROR_BAD_LENGTH. */ public WinNT.HANDLE CreateToolhelp32Snapshot(WinDef.DWORD dwFlags, WinDef.DWORD th32ProcessID);
/** * Controls whether the system will handle the specified types of serious errors or whether the process will handle them. * See: http://msdn.microsoft.com/en-us/library/ms680621%28VS.85%29.aspx * * @param uMode The process error mode. This parameter can be one or more of the following values. */ public int SetErrorMode(DWORD uMode);
/** * Retrieves the full name of the executable image for the specified * process. * * @param hProcess Handle to the process. * @param dwFlags Type of path format to return. * @param lpExeName On output, the path to the executable image. * @param lpdwSize On input, the size of lpExeName. On success, the * number of characters written to the buffer. * @return true if the function succeeds, false otherwise. */ boolean QueryFullProcessImageName( HANDLE hProcess, DWORD dwFlags, char[] lpExeName, IntByReference lpdwSize);
public BOOL EnumProcessModulesEx(HANDLE hProcess, DWORD[] hMods, int i, Pointer lpcbNeeded, DWORD dwFilterFlag);
public DWORD GetModuleFileNameEx(HANDLE hProcess, DWORD hModule, char[] szModName, DWORD nSize);
public boolean BitBlt(HDC hObject, int nXDest, int nYDest, int nWidth, int nHeight, HDC hObjectSource, int nXSrc, int nYSrc, DWORD dwRop);
DWORD GetPixel(HDC hdc, int nXPos, int nYPos);
HANDLE CreateSolidBrush(DWORD crColor);