/// <summary> /// Get the file path to the exe for the process which owns this window /// </summary> public static string GetProcessPath(this IInteropWindow interopWindow) { // TODO: fix for apps var processid = interopWindow.GetProcessId(); return(Kernel32Api.GetProcessPath(processid)); }
/// <summary> /// Create ClipboardNativeInfo to read /// </summary> /// <param name="clipboardAccessToken">IClipboardLock</param> /// <param name="formatId">uint</param> /// <returns>ClipboardNativeInfo</returns> public static ClipboardNativeInfo ReadInfo(this IClipboardAccessToken clipboardAccessToken, uint formatId) { clipboardAccessToken.ThrowWhenNoAccess(); var hGlobal = NativeMethods.GetClipboardData(formatId); if (hGlobal == IntPtr.Zero) { if (NativeMethods.IsClipboardFormatAvailable(formatId)) { throw new Win32Exception($"Format {formatId} not available."); } throw new Win32Exception(); } var memoryPtr = Kernel32Api.GlobalLock(hGlobal); if (memoryPtr == IntPtr.Zero) { throw new Win32Exception(); } return(new ClipboardNativeInfo { GlobalHandle = hGlobal, MemoryPtr = memoryPtr, FormatId = formatId }); }
public void TestOsVersionInfoEx() { var osVersionInfoEx = OsVersionInfoEx.Create(); Assert.True(Kernel32Api.GetVersionEx(ref osVersionInfoEx)); Assert.True(osVersionInfoEx.MajorVersion >= 6); }
/// <summary> /// Set the content for the specified format. /// You will need to "lock" (OpenClipboard) the clipboard before calling this. /// </summary> /// <param name="format">the format to set the content for</param> /// <param name="stream">MemoryStream with the content</param> public static void SetAsStream(string format, MemoryStream stream) { uint formatId; if (!Format2Id.TryGetValue(format, out formatId)) { formatId = RegisterFormat(format); } var length = stream.Length; var hGlobal = Kernel32Api.GlobalAlloc(GlobalMemorySettings.ZeroInit | GlobalMemorySettings.Movable, new UIntPtr((ulong)length)); if (hGlobal == IntPtr.Zero) { throw new Win32Exception(); } var memoryPtr = Kernel32Api.GlobalLock(hGlobal); try { if (memoryPtr == IntPtr.Zero) { throw new Win32Exception(); } // Fill the global memory Marshal.Copy(stream.GetBuffer(), 0, memoryPtr, (int)length); } finally { Kernel32Api.GlobalUnlock(hGlobal); } // Place the content on the clipboard NativeMethods.SetClipboardData(formatId, hGlobal); }
/// <summary> /// Factory for the write information /// </summary> /// <param name="clipboardAccessToken">IClipboardLock</param> /// <param name="formatId">uint with the format id</param> /// <param name="size">int with the size of the clipboard area</param> /// <returns>ClipboardNativeInfo</returns> public static ClipboardNativeInfo WriteInfo(this IClipboardAccessToken clipboardAccessToken, uint formatId, long size) { clipboardAccessToken.ThrowWhenNoAccess(); var hGlobal = Kernel32Api.GlobalAlloc(GlobalMemorySettings.ZeroInit | GlobalMemorySettings.Movable, new UIntPtr((ulong)size)); if (hGlobal == IntPtr.Zero) { throw new Win32Exception(); } var memoryPtr = Kernel32Api.GlobalLock(hGlobal); if (memoryPtr == IntPtr.Zero) { throw new Win32Exception(); } return(new ClipboardNativeInfo { GlobalHandle = hGlobal, MemoryPtr = memoryPtr, NeedsWrite = true, FormatId = formatId }); }
/// <summary> /// Retrieve the content for the specified format. /// You will need to "lock" (OpenClipboard) the clipboard before calling this. /// </summary> /// <param name="format">the format to retrieve the content for</param> /// <returns>MemoryStream</returns> public static MemoryStream GetAsStream(string format) { uint formatId; if (!Format2Id.TryGetValue(format, out formatId)) { formatId = RegisterFormat(format); } var hGlobal = NativeMethods.GetClipboardData(formatId); var memoryPtr = Kernel32Api.GlobalLock(hGlobal); try { if (memoryPtr == IntPtr.Zero) { throw new Win32Exception(); } var size = Kernel32Api.GlobalSize(hGlobal); var stream = new MemoryStream(size); stream.SetLength(size); // Fill the memory stream Marshal.Copy(memoryPtr, stream.GetBuffer(), 0, size); return(stream); } finally { Kernel32Api.GlobalUnlock(hGlobal); } }
/// <summary> /// 将值写入指定内存地址中 /// </summary> /// <param name="baseAddress">内存地址</param> /// <param name="PId">进程Id</param> /// <param name="value">要写入的值</param> public static void WriteMemoryValue(int baseAddress, int PId, int value) { IntPtr hProcess = Kernel32Api.OpenProcess(0x1F0FFF, false, PId); //0x1F0FFF 最高权限 Kernel32Api.WriteProcessMemory(hProcess, (IntPtr)baseAddress, new int[] { value }, 4, IntPtr.Zero); Kernel32Api.CloseHandle(hProcess); }
private void Test_GetOsVersionInfoEx() { var osVersionInfoEx = OsVersionInfoEx.Create(); Assert.True(Kernel32Api.GetVersionEx(ref osVersionInfoEx)); //Assert.NotEmpty(osVersionInfoEx.ServicePackVersion); }
void CloseDevice(IntPtr handle) { if (Environment.OSVersion.Version.Major > 5) { Kernel32Api.CancelIoEx(handle, IntPtr.Zero); } Kernel32Api.CloseHandle(handle); }
/// <summary> /// Cleanup this native info by unlocking the global handle /// </summary> public void Dispose() { Kernel32Api.GlobalUnlock(GlobalHandle); if (NeedsWrite) { // Place the content on the clipboard NativeMethods.SetClipboardData(FormatId, GlobalHandle); } }
/// <summary> /// Get the icon for a hWnd /// </summary> /// <typeparam name="TIcon">The return type for the icon, can be Icon, Bitmap or BitmapSource</typeparam> /// <param name="window">IInteropWindow</param> /// <param name="useLargeIcons">true to try to get a big icon first</param> /// <returns>TIcon</returns> public static TIcon GetIcon <TIcon>(this IInteropWindow window, bool useLargeIcons = false) where TIcon : class { if (window.IsApp()) { return(IconHelper.GetAppLogo <TIcon>(window)); } var icon = GetIconFromWindow <TIcon>(window, useLargeIcons); if (icon != null) { return(icon); } var processId = window.GetProcessId(); // Try to get the icon from the process file itself, if we can query the path var processPath = Kernel32Api.GetProcessPath(processId); if (processPath != null) { return(IconHelper.ExtractAssociatedIcon <TIcon>(processPath, useLargeIcon: useLargeIcons)); } // Look at the windows of the other similar named processes using (var process = Process.GetProcessById(processId)) { var processName = process.ProcessName; foreach (var possibleParentProcess in Process.GetProcessesByName(processName)) { var parentProcessWindow = InteropWindowFactory.CreateFor(possibleParentProcess.MainWindowHandle); icon = GetIconFromWindow <TIcon>(parentProcessWindow, useLargeIcons); if (icon != null) { return(icon); } possibleParentProcess.Dispose(); } } // Try to find another window, which belongs to the same process, and get the icon from there foreach (var otherWindow in InteropWindowQuery.GetTopWindows().Where(interopWindow => interopWindow.GetProcessId() == processId)) { if (otherWindow.Handle == window.Handle) { continue; } icon = GetIconFromWindow <TIcon>(otherWindow, useLargeIcons); if (icon != null) { return(icon); } } // Nothing found, REALLY! return(default(TIcon)); }
//读取内存中的值 /// <summary> /// 读取内存中的值 /// </summary> /// <param name="baseAddress">内存地址</param> /// <param name="processName">进程名</param> /// <returns>值</returns> public static int ReadMemoryValue(int baseAddress, string processName) { try { byte[] buffer = new byte[4]; IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); //获取缓冲区地址 IntPtr hProcess = Kernel32Api.OpenProcess(0x1F0FFF, false, GetPidByProcessName(processName)); Kernel32Api.ReadProcessMemory(hProcess, (IntPtr)baseAddress, byteAddress, 4, IntPtr.Zero); //将制定内存中的值读入缓冲区 Kernel32Api.CloseHandle(hProcess); return(Marshal.ReadInt32(byteAddress)); } catch { return(0); } }
IntPtr OpenDevice(string devicePath, DeviceModeType deviceMode, AccessModeType accessMode, ShareModeType shareMode) { var securityAttributes = Kernel32Api.SECURITY_ATTRIBUTES.Create(); var flags = 0; // FILE_FLAG_OVERLAPPED is used for async i/o //if (deviceMode == DeviceModeType.Overlapped) { flags = 0x40000000; //FILE_FLAG_OVERLAPPED; //} // internal const short FILE_SHARE_READ = 0x1; // internal const short FILE_SHARE_WRITE = 0x2; // may be required to set shareMode //dwCreationDisposition == 3 (OPEN_EXISTING) return(Kernel32Api.CreateFile(devicePath, (uint)accessMode, (int)shareMode, ref securityAttributes, 3, flags, 0)); }
/// <summary> /// Test if the window is owned by the current thread /// </summary> /// <param name="interopWindow">InteropWindow</param> /// <returns>bool true if the window is owned by the current thread</returns> public static bool IsOwnedByCurrentThread(this IInteropWindow interopWindow) { // Although the process id is returned, the following also reads the Thread-ID interopWindow.GetProcessId(); return(Kernel32Api.GetCurrentThreadId() == interopWindow.ThreadId); }
/// <summary> /// Test if the window is owned by the current process /// </summary> /// <param name="interopWindow">InteropWindow</param> /// <returns>bool true if the window is owned by the current process</returns> public static bool IsOwnedByCurrentProcess(this IInteropWindow interopWindow) { return(Kernel32Api.GetCurrentProcessId() == interopWindow.GetProcessId()); }
/// <summary> /// 关闭进程 /// </summary> /// <param name="ProcessId"></param> public static void CloseProcess(IntPtr ProcessId, int exitCode = 0) { IntPtr ip = Kernel32Api.OpenProcess(1, false, ProcessId.ToInt32()); Kernel32Api.TerminateProcess(ip, exitCode); }
/// <summary> /// Show all the running instances /// </summary> private static void ShowInstances() { var instanceInfo = new StringBuilder(); var index = 1; foreach (var process in Process.GetProcesses()) { try { if (process.ProcessName.ToLowerInvariant().Contains("greenshot")) { instanceInfo.AppendFormat("{0} : {1} (pid {2})", index++, Kernel32Api.GetProcessPath(process.Id), process.Id); instanceInfo.Append(Environment.NewLine); } } catch (Exception) { //Log.Debug().WriteLine(ex); } process.Dispose(); } // Placehold for the Extension IGreenshotLanguage language = null; // A dirty fix to make sure the messagebox is visible as a Greenshot window on the taskbar using (var multiInstanceForm = new Form { Icon = GreenshotResources.GetGreenshotIcon(), ShowInTaskbar = true, MaximizeBox = false, MinimizeBox = false, FormBorderStyle = FormBorderStyle.FixedDialog, Location = new Point(int.MinValue, int.MinValue), Text = language.TranslationOrDefault(l => l.Error), AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, StartPosition = FormStartPosition.CenterScreen }) { var flowLayoutPanel = new FlowLayoutPanel { AutoScroll = true, FlowDirection = System.Windows.Forms.FlowDirection.TopDown, WrapContents = false, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink }; var internalFlowLayoutPanel = new FlowLayoutPanel { AutoScroll = true, FlowDirection = System.Windows.Forms.FlowDirection.LeftToRight, WrapContents = false, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink }; var pictureBox = new PictureBox { Dock = DockStyle.Left, Image = SystemIcons.Error.ToBitmap(), SizeMode = PictureBoxSizeMode.AutoSize }; internalFlowLayoutPanel.Controls.Add(pictureBox); var textbox = new Label { Text = language.TranslationOrDefault(l => l.ErrorMultipleinstances) + Environment.NewLine + instanceInfo, AutoSize = true }; internalFlowLayoutPanel.Controls.Add(textbox); flowLayoutPanel.Controls.Add(internalFlowLayoutPanel); var cancelButton = new Button { Text = language.TranslationOrDefault(l => l.BugreportCancel), Dock = DockStyle.Bottom, Height = 20 }; flowLayoutPanel.Controls.Add(cancelButton); multiInstanceForm.Controls.Add(flowLayoutPanel); multiInstanceForm.CancelButton = cancelButton; multiInstanceForm.ShowDialog(); } }
/// <summary> /// Process the commandline arguments /// </summary> /// <param name="isAlreadyRunning">bool which specifies if the application is already running</param> /// <param name="arguments">string array with the arguments</param> public void Process(bool isAlreadyRunning, string[] arguments) { var filesToOpen = new List <string>(); if (arguments.Length > 0 && Log.IsDebugEnabled()) { Log.Debug().WriteLine("Greenshot arguments: " + string.Join(",", arguments.Select(s => $"\"{s}\""))); } for (var argumentNr = 0; argumentNr < arguments.Length; argumentNr++) { var argument = arguments[argumentNr]; switch (argument) { case "/help": case "/h": case "/?": break; } // Help if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) { // Try to attach to the console var attachedToConsole = Kernel32Api.AttachConsole(Kernel32Api.ATTACHCONSOLE_ATTACHPARENTPROCESS); // If attach didn't work, open a console if (!attachedToConsole) { Kernel32Api.AllocConsole(); } var helpOutput = new StringBuilder(); helpOutput.AppendLine(); helpOutput.AppendLine("Greenshot commandline options:"); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t/help"); helpOutput.AppendLine("\t\tThis help."); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t/exit"); helpOutput.AppendLine("\t\tTries to close all running instances."); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t/reload"); helpOutput.AppendLine("\t\tReload the configuration of Greenshot."); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t/language [language code]"); helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US."); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t/inidirectory [directory]"); helpOutput.AppendLine("\t\tSet the directory where the greenshot.ini should be stored & read."); helpOutput.AppendLine().AppendLine(); helpOutput.AppendLine("\t[filename]"); helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance"); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/capture <region|window|fullscreen>[,Destination]"); helpOutput.AppendLine("\t\tStart capture from command line. Use /capture without arguments for more info. Greenshot must be running"); Console.WriteLine(helpOutput.ToString()); // If attach didn't work, wait for key otherwise the console will close to quickly if (!attachedToConsole) { Console.ReadKey(); } // TODO: //FreeMutex(); return; } if (argument.ToLower().Equals("/exit")) { // unregister application on uninstall (allow uninstall) try { Log.Info().WriteLine("Sending all instances the exit command."); // Pass Exit to running instance, if any GreenshotClient.Exit(); } catch (Exception e) { Log.Warn().WriteLine(e, "Exception by exit."); } // TODO: //FreeMutex(); return; } // Reload the configuration if (argument.ToLower().Equals("/reload")) { // Modify configuration Log.Info().WriteLine("Reloading configuration!"); try { // Update running instances GreenshotClient.ReloadConfig(); } catch (Exception ex) { Log.Error().WriteLine(ex, "Couldn't reload configuration."); } // TODO: /* * finally * { * FreeMutex(); * } */ return; } // Stop running if (argument.ToLower().Equals("/norun")) { // Make an exit possible // TODO: //FreeMutex(); return; } // Language if (argument.ToLower().Equals("/language")) { _coreConfiguration.Language = arguments[++argumentNr]; continue; } // Setting the INI-directory if (argument.ToLower().Equals("/inidirectory")) { // Change the ini config location //IniConfig.Current.IniDirectory = arguments[++argumentNr]; continue; } // Capture from command line, only accept as first argument if (arguments.Length > 0 && arguments[0].ToLower().Equals("/capture")) { // Try to attach to the console bool attachedToConsole = Kernel32Api.AttachConsole(Kernel32Api.ATTACHCONSOLE_ATTACHPARENTPROCESS); // If attach didn't work, open a console if (!attachedToConsole) { Kernel32Api.AllocConsole(); } // Display help for /capture command if not enough arguments if (arguments.Length < 2) { var helpOutput = new StringBuilder(); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("Usage for /capture:"); helpOutput.AppendLine("\t/capture <region|window|fullscreen>[,Destination]"); helpOutput.AppendLine(); helpOutput.AppendLine("\tDestinations: (CaseSensitive!)"); helpOutput.AppendFormat( "\t\t{0,-16}\t==>\t{1}{2}", "\"External CmdName\"", "External Command like MS Paint", Environment.NewLine ); foreach (var destination in ServiceLocator.Current.GetAllInstances <IDestination>()) { helpOutput.AppendFormat( "\t\t{0,-16}\t==>\t{1}{2}", destination.Designation, destination.Description, Environment.NewLine ); } helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\tUsage examples:"); helpOutput.AppendLine("\t\t/capture window,FileNoDialog\t\t(capture window, save in default screenshot folder)"); helpOutput.AppendLine("\t\t/capture fullscreen\t\t\t(capture fullscreen, use destination from settings)"); helpOutput.AppendLine("\t\t/capture region,Clipboard\t\t(capture region directly to clipboard)"); helpOutput.AppendLine("\t\t/capture fullscreen,Picker\t\t(capture fullscreen, ask what to do)"); helpOutput.AppendLine("\t\t/capture region,\"External MS Paint\"\t(capture region and send to external command 'MS Paint')"); helpOutput.AppendLine(); helpOutput.AppendLine("\tShortcut path examples for Windows:"); helpOutput.AppendLine("\t\t\"C:\\Program Files\\Greenshot\\Greenshot.exe\" /capture region,\"External MS Paint\""); helpOutput.AppendLine("\t\tD:\\Programme\\Greenshot\\Greenshot.exe /capture fullscreen,FileNoDialog"); helpOutput.AppendLine(); Console.WriteLine(helpOutput.ToString()); // If attach didn't work, wait for key otherwise the console will close to quickly if (!attachedToConsole) { Console.ReadKey(); } } else if (!isAlreadyRunning) { Console.WriteLine("{0}{0}Please start Greenshot first", Environment.NewLine); // If attach didn't work, wait for key otherwise the console will close to quickly if (!attachedToConsole) { Console.ReadKey(); } } else { GreenshotClient.Capture(arguments[1]); } // TODO: //FreeMutex(); return; } // Files to open filesToOpen.Add(argument); } if (isAlreadyRunning) { // We didn't initialize the language yet, do it here just for the message box if (filesToOpen.Count > 0) { GreenshotClient.OpenFiles(filesToOpen); } else { //ShowInstances(); } // TODO: //FreeMutex(); //Application.Exit(); return; } }