//[Test] //public void FindSmallestBinaryWithResources() //{ // FindSmallestBinaryWithResources( // Environment.SystemDirectory, // "*.exe", // Kernel32.ResourceTypes.RT_MENU); //} private void FindSmallestBinaryWithResources( string path, string ext, Kernel32.ResourceTypes rt) { long smallest = 0; string[] files = Directory.GetFiles(path, ext); foreach (string filename in files) { try { using (ResourceInfo ri = new ResourceInfo()) { ri.Load(filename); if (!ri.Resources.ContainsKey(new ResourceId(rt))) continue; FileInfo fi = new FileInfo(filename); //if (fi.Length < smallest || smallest == 0) //{ Console.WriteLine("{0} {1}", filename, new FileInfo(filename).Length); smallest = fi.Length; // } break; } } catch { } } }
IntPtr GetProcessHandle(Kernel32.ProcessAccessFlags access, bool throwIfExited) { if (_haveProcessHandle) { if (throwIfExited) { // Since haveProcessHandle is true, we know we have the process handle // open with at least SYNCHRONIZE access, so we can wait on it with // zero timeout to see if the process has exited. ProcessWaitHandle waitHandle = null; try { waitHandle = new ProcessWaitHandle(_processHandle); if (waitHandle.WaitOne(0, false)) { throw new InvalidOperationException("Process has exited"); } } finally { waitHandle?.Close(); } } return _processHandle; } var handle = Kernel32.OpenProcess(access, false, _inner.Id); if (throwIfExited && (access & Kernel32.ProcessAccessFlags.QueryInformation) != 0) { int exitCode; if (Kernel32.GetExitCodeProcess(handle, out exitCode) && exitCode != Kernel32.STILL_ACTIVE) { throw new InvalidOperationException("Process has exited"); } } return handle; }
public static void CopyFile(FileInfo source, FileInfo destination, Kernel32.CopyFileOptions options, Kernel32.CopyFileCallback callback, object state) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if ((options & ~Kernel32.CopyFileOptions.All) != 0) throw new ArgumentOutOfRangeException("options"); new FileIOPermission( FileIOPermissionAccess.Read, source.FullName).Demand(); new FileIOPermission( FileIOPermissionAccess.Write, destination.FullName).Demand(); Kernel32.CopyProgressRoutine cpr = callback == null ? null : new Kernel32.CopyProgressRoutine(new Kernel32.CopyProgressData( source, destination, callback, state).CallbackHandler); bool cancel = false; if (!Kernel32.CopyFileEx(source.FullName, destination.FullName, cpr, IntPtr.Zero, ref cancel, (int)options)) { throw new Win32Exception(); } }
public static SafeMemoryMappedFileHandle CreateFileMapping( IntPtr hFile, ref Kernel32.SECURITY_ATTRIBUTES securityAttributes, int pageProtection, long maximumSize, string name) { // split the long into two ints int capacityHigh, capacityLow; SplitLong(maximumSize, out capacityHigh, out capacityLow); return Interop.Kernel32.CreateFileMapping(hFile, ref securityAttributes, pageProtection, capacityHigh, capacityLow, name); }
/// <summary> /// A new executable manifest. /// </summary> /// <param name="manifestType">Manifest type.</param> public ManifestResource(Kernel32.ManifestType manifestType) : base(IntPtr.Zero, IntPtr.Zero, new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST), new ResourceId((uint) manifestType), Kernel32.LANG_NEUTRAL, 0) { _manifest = new XmlDocument(); _manifest.LoadXml( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\" />"); _size = Encoding.UTF8.GetBytes(_manifest.OuterXml).Length; }
public static void CopyFile(FileInfo source, FileInfo destination, Kernel32.CopyFileOptions options) { CopyFile(source, destination, options, null); }
private List<Track> BuildCDTracks(Kernel32.CDROM_TOC_CD_TEXT_DATA Data) { int numTracks = GetNumTracks(); if (numTracks == -1) return null; List<Track> tracks = new List<Track>(); List<string> titles = new List<string>(); List<string> artists = new List<string>(); List<string> genres = new List<string>(); string item = string.Empty; try { Debug.Write("CD_TEXT info dump BEGIN:"); for (int i = 0; i < Data.Descriptors.MaxIndex; i++) { string line = ""; foreach (char c in Data.Descriptors[i].Text) { if (c != '\0') line += c; else line += "."; } Debug.Write(line); } Debug.Write("CD_TEXT info dump END"); for (int i = 0; i < Data.Descriptors.MaxIndex; i++) { Kernel32.CDROM_TOC_CD_TEXT_DATA_BLOCK cdrom_toc_cd_text_data_block = Data.Descriptors[i]; foreach (char ch in cdrom_toc_cd_text_data_block.Text) { if (ch != '\0') { item = item + ch; } else if (!string.IsNullOrEmpty(item)) { switch (cdrom_toc_cd_text_data_block.PackType) { case Kernel32.CDROM_CD_TEXT_PACK.ALBUM_NAME: titles.Add(item); item = string.Empty; break; case Kernel32.CDROM_CD_TEXT_PACK.GENRE: genres.Add(item); item = string.Empty; break; case Kernel32.CDROM_CD_TEXT_PACK.PERFORMER: artists.Add(item); item = string.Empty; break; default: item = string.Empty; break; } } } } } catch (IndexOutOfRangeException) { } finally { } //int max = titles.Count; //if (artists.Count != 0 && max > artists.Count) // max = artists.Count; //if (genres.Count != 0 && max > genres.Count) // max = genres.Count; if (numTracks > 0) { string mainTitle = (titles.Count > 0) ? titles[0] : null; string mainArtist = (artists.Count > 0) ? artists[0] : null; string mainGenre = (genres.Count > 0) ? genres[0] : null; for (int i = 1; i <= numTracks; i++) { Track track = new Track(); track.Index = i; try { if (titles.Count > i || titles.Count > i || titles.Count > i) { if (titles.Count > i) track.Title = titles[i]; if (artists.Count > i) track.Artist = artists[i]; if (genres.Count > i) track.Genre = genres[i]; if (!string.IsNullOrEmpty(mainTitle)) { track.Album = mainTitle; } if (string.IsNullOrEmpty(track.Artist) && !string.IsNullOrEmpty(mainArtist)) { track.Artist = mainArtist; } } } catch { } tracks.Add(track); } } return tracks; }
/// <summary> /// A well-known resource-type identifier. /// </summary> /// <param name="value">A well known resource type.</param> internal ResourceId(Kernel32.ResourceTypes value) { Id = (IntPtr) value; }
/// <summary> /// 关闭句柄 /// </summary> /// <param name="handle"></param> /// <returns></returns> public static bool Close(this IntPtr handle) { return(Kernel32.CloseHandle(handle)); }
public static unsafe extern SafeDesktopHandle CreateDesktopEx( string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, DesktopCreationFlags dwFlags, Kernel32.ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa, uint ulHeapSize, IntPtr pvoid = default(IntPtr));
public static extern unsafe NTSTATUS NtOpenSection( out SafeNTObjectHandle sectionHandle, Kernel32.ACCESS_MASK desiredAccess, [Friendly(FriendlyFlags.In)] OBJECT_ATTRIBUTES* objectAttributes);
public static extern unsafe IntPtr CreateDialogIndirectParam( Kernel32.SafeLibraryHandle hInstance, DLGTEMPLATE* lpTemplate, IntPtr hWndParent, DialogProc lpDialogFunc, IntPtr lParamInit);
private static bool ConsoleCloseEvent(Kernel32.CtrlType sig) { app.Exit(); return true; }
private static DialogResult ShowCore(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool showHelp) { if (!ClientUtils.IsEnumValid(buttons, (int)buttons, (int)MessageBoxButtons.OK, (int)MessageBoxButtons.RetryCancel)) { throw new InvalidEnumArgumentException(nameof(buttons), (int)buttons, typeof(MessageBoxButtons)); } // valid values are 0x0 0x10 0x20 0x30 0x40, chop off the last 4 bits and check that it's between 0 and 4. if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(icon, /*numBitsToShift*/ 4, /*min*/ 0x0, /*max*/ 0x4)) { throw new InvalidEnumArgumentException(nameof(icon), (int)icon, typeof(MessageBoxIcon)); } // valid values are 0x0 0x100, 0x200, chop off the last 8 bits and check that it's between 0 and 2. if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(defaultButton, /*numBitsToShift*/ 8, /*min*/ 0x0, /*max*/ 0x2)) { throw new InvalidEnumArgumentException(nameof(defaultButton), (int)defaultButton, typeof(DialogResult)); } // options intentionally not verified because we don't expose all the options Win32 supports. if (!SystemInformation.UserInteractive && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0) { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } if (owner != null && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) { throw new ArgumentException(SR.CantShowMBServiceWithOwner, nameof(options)); } if (showHelp && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) { throw new ArgumentException(SR.CantShowMBServiceWithHelp, nameof(options)); } MB style = (showHelp) ? MB.HELP : 0; style |= (MB)buttons | (MB)icon | (MB)defaultButton | (MB)options; IntPtr handle = IntPtr.Zero; if (showHelp || ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0)) { if (owner is null) { handle = GetActiveWindow(); } else { handle = Control.GetSafeHandle(owner); } } IntPtr userCookie = IntPtr.Zero; if (Application.UseVisualStyles) { // CLR4.0 or later, shell32.dll needs to be loaded explicitly. if (Kernel32.GetModuleHandleW(Libraries.Shell32) == IntPtr.Zero) { if (Kernel32.LoadLibraryFromSystemPathIfAvailable(Libraries.Shell32) == IntPtr.Zero) { int lastWin32Error = Marshal.GetLastWin32Error(); throw new Win32Exception(lastWin32Error, string.Format(SR.LoadDLLError, Libraries.Shell32)); } } // Activate theming scope to get theming for controls at design time and when hosted in browser. // NOTE: If a theming context is already active, this call is very fast, so shouldn't be a perf issue. userCookie = ThemingScope.Activate(Application.UseVisualStyles); } Application.BeginModalMessageLoop(); DialogResult result; try { result = Win32ToDialogResult(MessageBoxW(new HandleRef(owner, handle), text, caption, style)); } finally { Application.EndModalMessageLoop(); ThemingScope.Deactivate(userCookie); } // Right after the dialog box is closed, Windows sends WM_SETFOCUS back to the previously active control // but since we have disabled this thread main window the message is lost. So we have to send it again after // we enable the main window. User32.SendMessageW(new HandleRef(owner, handle), User32.WM.SETFOCUS); return(result); }
/// <summary> /// Event handler that's called when the window is loaded; shows <see cref="_layeredWindow" /> and installs the mouse hook via /// <see cref="User32.SetWindowsHookEx" />. /// </summary> /// <param name="e">Arguments associated with this event.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); _initialized = true; UpdateLayeredBackground(); _layeredWindow.Show(); _layeredWindow.Enabled = false; // Installs the mouse hook if (!_hookInstalled) { using (Process curProcess = Process.GetCurrentProcess()) { using (ProcessModule curModule = curProcess.MainModule) { _hookproc = MouseHookCallback; _hookId = User32.SetWindowsHookEx(WH.WH_MOUSE_LL, _hookproc, Kernel32.GetModuleHandle(curModule.ModuleName), 0); } } _hookInstalled = true; } }
public static void CopyFile(FileInfo source, FileInfo destination, Kernel32.CopyFileOptions options, Kernel32.CopyFileCallback callback) { CopyFile(source, destination, options, callback, null); }
public static unsafe extern SafeDesktopHandle CreateDesktop( string lpszDesktop, string lpszDevice, IntPtr pDevmode, DesktopCreationFlags dwFlags, Kernel32.ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa);
public static unsafe extern SafeWindowStationHandle CreateWindowStation( string lpwinsta, WindowStationCreationFlags dwFlags, Kernel32.ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa);
/// <summary> /// Load a manifest resource from an executable file. /// </summary> /// <param name="filename">Name of an executable file (.exe or .dll).</param> /// <param name="manifestType">Manifest resource type.</param> public void LoadFrom(string filename, Kernel32.ManifestType manifestType) { base.LoadFrom(filename, new ResourceId((uint) manifestType), new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST), Kernel32.LANG_NEUTRAL); }
public static extern SafeWindowStationHandle OpenWindowStation( string lpszWinSta, [MarshalAs(UnmanagedType.Bool)] bool fInherit, Kernel32.ACCESS_MASK dwDesiredAccess);
/// <summary> /// A well-known resource-type identifier. /// </summary> /// <param name="value">A well known resource type.</param> public ResourceId(Kernel32.ResourceTypes value) { Id = (IntPtr) value; }
public static extern SafeDesktopHandle OpenDesktop( string lpszDesktop, DesktopCreationFlags dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fInherit, Kernel32.ACCESS_MASK dwDesiredAccess);
public static extern void GetSystemInfo(out Kernel32.SYSTEM_INFO lpSystemInfo);
private void DebugWindow_Load(object sender, EventArgs e) { data.AutoGenerateColumns = true; string Password = (!String.IsNullOrEmpty(FileAccountSave.UserHashedPassword)) ? "True" : "False"; string ProxyStatus = (!String.IsNullOrEmpty(FileSettingsSave.Proxy)) ? "False" : "True"; string RPCStatus = (!String.IsNullOrEmpty(FileSettingsSave.RPC)) ? "False" : "True"; string Antivirus = String.Empty; string Firewall = String.Empty; string AntiSpyware = String.Empty; if (!DetectLinux.LinuxDetected()) { try { Antivirus = (String.IsNullOrEmpty(AntivirusInstalled())) ? "---" : AntivirusInstalled(); Firewall = (String.IsNullOrEmpty(AntivirusInstalled("FirewallProduct"))) ? "Built-In" : AntivirusInstalled("FirewallProduct"); AntiSpyware = (String.IsNullOrEmpty(AntivirusInstalled("AntiSpywareProduct"))) ? "---" : AntivirusInstalled("AntiSpywareProduct"); } catch { Antivirus = "Unknown"; Firewall = "Unknown"; AntiSpyware = "Unknown"; } } string OS = ""; if (DetectLinux.LinuxDetected()) { OS = DetectLinux.Distro(); } else { OS = Environment.OSVersion.VersionString; } string UpdateSkip = ""; if (FileSettingsSave.IgnoreVersion == Application.ProductVersion || FileSettingsSave.IgnoreVersion == String.Empty) { UpdateSkip = "False"; } else { UpdateSkip = FileSettingsSave.IgnoreVersion; } string FirewallRuleStatus = ""; if (String.IsNullOrEmpty(FileSettingsSave.FirewallStatus)) { FirewallRuleStatus = "Not Exlcuded"; } else { FirewallRuleStatus = FileSettingsSave.FirewallStatus; } long memKb = 0; ulong lpFreeBytesAvailable = 0; List <string> GPUs = new List <string>(); string Win32_Processor = ""; if (!DetectLinux.LinuxDetected()) { Kernel32.GetPhysicallyInstalledSystemMemory(out memKb); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController"); string graphicsCard = string.Empty; foreach (ManagementObject mo in searcher.Get()) { foreach (PropertyData property in mo.Properties) { GPUs.Add(property.Value.ToString()); } } Win32_Processor = (from x in new ManagementObjectSearcher("SELECT Name FROM Win32_Processor").Get().Cast <ManagementObject>() select x.GetPropertyValue("Name")).FirstOrDefault().ToString(); Kernel32.GetDiskFreeSpaceEx(FileSettingsSave.GameInstallation, out lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); } var Win32_VideoController = string.Join(" | ", GPUs); var settings = new List <ListType> { new ListType { Name = "InstallationDirectory", Value = FileSettingsSave.GameInstallation }, new ListType { Name = "Launcher Version", Value = Application.ProductVersion }, new ListType { Name = "Credentials Saved", Value = Password }, new ListType { Name = "Language", Value = FileSettingsSave.Lang }, new ListType { Name = "Skipping Update", Value = UpdateSkip }, new ListType { Name = "Disable Proxy", Value = ProxyStatus }, new ListType { Name = "Disable RPC", Value = RPCStatus }, new ListType { Name = "Firewall Rule", Value = FirewallRuleStatus }, new ListType { Name = "", Value = "" }, new ListType { Name = "Server Name", Value = ServerName }, new ListType { Name = "Server Address", Value = ServerIP }, new ListType { Name = "CDN Address", Value = FileSettingsSave.CDN }, new ListType { Name = "ProxyPort", Value = Self.ProxyPort.ToString() }, new ListType { Name = "", Value = "" }, }; if (!DetectLinux.LinuxDetected()) { settings.AddRange(new[] { new ListType { Name = "Antivirus", Value = Antivirus }, new ListType { Name = "Firewall Application", Value = Firewall }, new ListType { Name = "AntiSpyware", Value = AntiSpyware }, new ListType { Name = "", Value = "" }, new ListType { Name = "CPU", Value = Win32_Processor }, new ListType { Name = "GPU", Value = Win32_VideoController }, new ListType { Name = "RAM", Value = (memKb / 1024).ToString() + "MB" }, new ListType { Name = "Disk Space Left", Value = FormatFileSize(lpFreeBytesAvailable) }, new ListType { Name = "", Value = "" } }); } settings.AddRange(new[] { new ListType { Name = "HWID", Value = Security.FingerPrint.Value() }, new ListType { Name = "Operating System", Value = OS }, new ListType { Name = "Environment Version", Value = Environment.OSVersion.Version.ToString() }, new ListType { Name = "Screen Resolution", Value = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height } }); data.DataSource = settings; DataGridViewCellStyle style = new DataGridViewCellStyle { Font = new Font(data.Font, FontStyle.Regular) }; data.Columns[0].DefaultCellStyle = style; data.Columns[0].Width += 50; int size_x = 452; int size_y = 580; data.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.Size = new Size(size_x, size_y); }