public ExceptionBoxResult ShowDialog(params ExceptionBoxButtons[] buttons) { if (App.Current.MainWindow != this) { Owner = App.Current.MainWindow; WindowStartupLocation = WindowStartupLocation.CenterOwner; } else { WindowStartupLocation = WindowStartupLocation.CenterScreen; } text.Text = Message; if (IsWarning) { image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Warning.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } else { image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Error.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } // This isn't currently tied to ExceptionMessage because there are some instances where exceptions are shown // that probably are not very report worthy... decisions, decisions if (ShowReportInstructions) { reportingGrid.Visibility = Visibility.Visible; } else { reportingGrid.Visibility = Visibility.Collapsed; } if (String.IsNullOrEmpty(Path)) { folderGrid.Visibility = Visibility.Collapsed; } else if (!String.IsNullOrEmpty(Path)) { folderText.Text = Path; } if (String.IsNullOrEmpty(ExceptionMessage)) { exceptionGrid.Visibility = Visibility.Collapsed; } else { exceptionText.Text = ExceptionMessage; } if (!String.IsNullOrEmpty(ExceptionMessage) || !IsWarning || ShowReportInstructions) { linkBar.Visibility = Visibility.Visible; } else { linkBar.Visibility = Visibility.Collapsed; } Button lastButton = null; foreach (var choice in buttons) { lastButton = new Button(); lastButton.Content = choice.ToString(); switch (choice) { case ExceptionBoxButtons.Quit: lastButton.Click += quit_Click; _result = ExceptionBoxResult.Quit; break; case ExceptionBoxButtons.Cancel: lastButton.Click += cancel_Click; _result = ExceptionBoxResult.Cancel; break; case ExceptionBoxButtons.Continue: lastButton.Click += continue_Click; _result = ExceptionBoxResult.Continue; break; case ExceptionBoxButtons.OK: lastButton.Click += ok_Click; _result = ExceptionBoxResult.OK; break; default: lastButton.Click += quit_Click; _result = ExceptionBoxResult.Quit; break; } buttonStack.Children.Add(lastButton); } lastButton.IsDefault = true; base.ShowDialog(); return(_result); }
private static ImageSource IconToImageSource(Icon icon) { return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions())); }
protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.Icon = Imaging.CreateBitmapSourceFromHIcon(Properties.Resources._1.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); }
public ConfirmationBox() { InitializeComponent(); _result = ConfirmationResult.Cancel; image.Source = Imaging.CreateBitmapSourceFromHIcon(SystemIcons.Question.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); }
// Funzione eseguita da un thread in background: riceve dati dal socket public void SocketThreadListen() { int n = 0; try { Byte[] readBuffer = new Byte[1024]; while (!stop) { Console.WriteLine("In attesa di ricevere dati dal server..."); // Ricezione del tipo di modifica effettuata n = Stream.Read(readBuffer, 0, sizeof(ushort)); if (!readSuccessful(n, sizeof(ushort))) { return; } // Conversione del buffer nell'ordine dei byte dell'host (Precedentemente era in ordine di rete) ushort conv_mod = BitConverter.ToUInt16(readBuffer, 0); int ModificationType = IPAddress.NetworkToHostOrder((short)conv_mod); Console.WriteLine("Tipo della modifica: {0}", ModificationType); // Ricezione del PID del processo. E' una DWORD che ha dimensioni pari ad uint n = Stream.Read(readBuffer, 0, sizeof(uint)); if (!readSuccessful(n, sizeof(uint))) { return; } uint PID = BitConverter.ToUInt32(readBuffer, 0); Console.WriteLine("PID: {0}", PID); // Switch sul tipo di modifica switch (ModificationType) { // CASO 0: Aggiunta di una nuova applicazione case 0: // Lettura della lunghezza del nome dell'applicazione n = Stream.Read(readBuffer, 0, sizeof(int)); if (!readSuccessful(n, sizeof(uint))) { return; } // Conversione della lunghezza del nome in ordine dell'host int conv_length = BitConverter.ToInt32(readBuffer, 0); Console.WriteLine("Lunghezza convertita: {0}", conv_length); int NameLength = IPAddress.NetworkToHostOrder(conv_length); Console.WriteLine("Lunghezza nome: {0}", NameLength); Byte[] NameBuffer = new Byte[NameLength]; String AppName = String.Empty; // Lettura del nome dell'applicazione n = Stream.Read(NameBuffer, 0, NameLength); if (!readSuccessful(n, NameLength)) { return; } try { // Conversione in stringa AppName = System.Text.UnicodeEncoding.Unicode.GetString(NameBuffer); AppName = AppName.Replace("\0", String.Empty); } catch (ArgumentException) { AppName = "Nessun nome"; } Console.WriteLine("Nome dell'applicazione: {0}", AppName); // Lettura della lunghezza dell'icona n = Stream.Read(readBuffer, 0, sizeof(int)); if (!readSuccessful(n, sizeof(uint))) { return; } AppItem app = new AppItem(TabManager.MyTab.MainWndw.DefaultIcon); app.PID = PID; app.Name = AppName; int conv_icon = BitConverter.ToInt32(readBuffer, 0); int IconLength = IPAddress.HostToNetworkOrder(conv_icon); Console.WriteLine("Lunghezza dell'icona: {0}", IconLength); // Se la dimensione è valida la si sostituisce a quella di default if (IconLength != 0 && IconLength < 1048576) { Console.WriteLine("Icona valida trovata"); // Lettura dell'icona dallo stream in blocchi da 1024 byte Byte[] BufferIcon = new Byte[IconLength]; int TotalRead = 0; int ToRead = 1024; while (TotalRead != IconLength) { if (ToRead > IconLength - TotalRead) { ToRead = IconLength - TotalRead; } n = Stream.Read(BufferIcon, TotalRead, ToRead); if (n == 0) { Console.WriteLine("Connessione persa durante la lettura dell'icona"); return; } TotalRead += n; } if (!readSuccessful(TotalRead, IconLength)) { return; } //in C# è necessario creare un blocco unsafe per usare i puntatori nativi C e l'aritmetica dei puntatori unsafe { //fixed consente di assegnare ad un puntatore C l'indirizzo di una variabile gestita. //poiché le variabili gestite possono essere spostate dal garbage collector, questo //impedisce che ciò avvenga. fixed(byte *buffer = &BufferIcon[0]) { IntPtr Hicon = CreateIconFromResourceEx((IntPtr)buffer, (uint)IconLength, 1, 0x00030000, 48, 48, 0); if (Hicon != null) { BitmapFrame bitmap = BitmapFrame.Create(Imaging.CreateBitmapSourceFromHIcon(Hicon, new Int32Rect(0, 0, 48, 48), BitmapSizeOptions.FromEmptyOptions())); if (bitmap.CanFreeze) { bitmap.Freeze(); app.Icon = bitmap; } DestroyIcon(Hicon); } } } } // Aggiunta di una nuova applicazione e notifica del cambiamento nella lista TabManager.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { lock (TabManager.Applications) { //aggiungo l'app alla ObsCollection Applications<AppItem> collegata alla ListView di TabManager TabManager.Applications.Add(app); } })); break; // Caso 1: rimozione di un'applicazione case 1: Console.WriteLine("Modifica: Rimozione"); // Rimozione dell'applicazione dalla lista Monitor.Enter(TabManager.Applications); foreach (AppItem appItem in TabManager.Applications) { if (appItem.PID == PID) { Console.WriteLine("Rimozione applicazione: {0}", appItem.Name); Monitor.Exit(TabManager.Applications); this.TabManager.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { lock (TabManager.Applications) { this.TabManager.Applications.Remove(appItem); } })); Monitor.Enter(TabManager.Applications); break; } } Monitor.Exit(TabManager.Applications); break; // Caso 3: cambio di focus case 2: Console.WriteLine("Modifica: Change Focus"); // Pulizia della selezione precedente this.TabManager.MyTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { this.TabManager.Applist.SelectedItem = null; })); // Applicazione che perde il focus this.TabManager.MyTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { // Aggiornamento lista app in foreground int index = this.TabManager.MyTab.MainWndw.AppsInFocus.IndexOf(new AppInFocus(TabManager.MyTab.AppInFocus)); if (index != -1) { //if (--this.TabManager.TabManager.MainWndw.AppsInFocus[index].Count <= 0) this.TabManager.MyTab.MainWndw.AppsInFocus.RemoveAt(index); } })); // Ricerca delle applicazioni coinvolte nel cambiamento Monitor.Enter(TabManager.Applications); foreach (AppItem appItem in TabManager.Applications) { // Applicazione che guadagna il focus if (appItem.PID == PID) { Console.WriteLine("Pid: {0} - applicazione: {1}", PID, appItem.Name); Monitor.Exit(TabManager.Applications); this.TabManager.MyTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { lock (TabManager.Applications) { // Evidenziazione elemento nella tab appItem.HasFocus = true; this.TabManager.Applist.SelectedItem = appItem; this.TabManager.MyTab.AppInFocus = appItem.Name; // Aggiornamento lista delle app in foreground AppInFocus newapp = new AppInFocus(appItem.Name); this.TabManager.MyTab.MainWndw.AppsInFocus.Add(newapp); this.TabManager.MyTab.MainWndw.AppsInFocusBox.SelectedItem = newapp; } })); Monitor.Enter(TabManager.Applications); } else if (appItem.HasFocus) { appItem.HasFocus = false; } } Monitor.Exit(TabManager.Applications); // Aggiornamento delle percentuali TabManager.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { TabManager.PercentageRefresh(); })); break; case 3: break; default: Console.WriteLine("Modifica sconosciuta"); break; } } Console.WriteLine("Thread - terminata ricezione dati dal server"); } catch (NullReferenceException) { ExceptionHandler.ReceiveConnectionError(TabManager); } catch (IOException) { ExceptionHandler.ReceiveConnectionError(TabManager); } catch (ObjectDisposedException) { ExceptionHandler.ReceiveConnectionError(TabManager); } catch (ArgumentOutOfRangeException) { ExceptionHandler.ReceiveConnectionError(TabManager); } catch (OutOfMemoryException) { ExceptionHandler.MemoryError(TabManager.MyTab.MainWndw); } }
public static ImageSource ToImageSource(this System.Drawing.Icon icon) => Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
private BitmapSource IconToImage(System.Drawing.Icon icon) { return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
public MainWindow() { AppDomain.CurrentDomain.UnhandledException += (sender, e) => { try { MessageBox.Show("Caught an unhandled exception. This should never ever happen " + "so please report this using the GitHub issue tracker. " + "Just attach the ssi.log file in the directory where I'm located and " + "you should be good to go. Thanks in advance.", "Uh-oh"); using (StreamWriter logfile = new StreamWriter("ssi.log")) { logfile.WriteLine("Unhandled exception at {0}: {1}", DateTime.Now, ((Exception)e.ExceptionObject).ToString()); } } catch { // So, uhm, yeah … we're screwed. Time to panic \o/ MessageBox.Show( "Caught an exception while trying to handle another unhandled exception. " + "I'm really sorry (this is the point where you may want to panic).", "What the …"); } Environment.Exit(1); }; InitializeComponent(); InfoIcon.Source = Imaging.CreateBitmapSourceFromHIcon(SystemIcons.Information.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ButtonUnelevated.Visibility = Visibility.Hidden; _lockInstallControlsState = false; _lockUpdateControlsState = false; _lockApplyControlsState = false; bool invalidSteamLocation = false; try { _steamClient = new ClientProperties(); TextSteamLocation.Text = _steamClient.GetInstallPath(); } catch (Exception e) { MessageBox.Show(e.Message, "Error while trying to find your Stem installation"); invalidSteamLocation = true; } _noCatalogWarning = new TextBlock { Text = "Skin catalog file not found. Try clicking the button in the top right corner.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; _noInstalledCatalogWarning = new TextBlock { Text = "Looks like you don't have any skin installed. Head over to the first tab and install one.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; _errorReadingCatalogWarning = new TextBlock { Text = "Error while trying to read the skin catalog file. You should try redownloading it in the top right corner.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; _errorReadingInstalledCatalogWarning = new TextBlock { Text = "Error while trying to read the skin catalog file. Try deleting it (located in " + Path.Combine((invalidSteamLocation) ? "your Steam install location" : (_steamClient.GetInstallPath()), "skins", "skins.xml") + ") and hope for the best.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; _allSkinsInstalled = new TextBlock { Text = "You already have every available skin installed. Not bad. You may try refreshing the available " + "skin list using the button in the top right button though.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; TextBlock invalidSteamLocationWarning = new TextBlock { Text = "Couldn't find Steam and, thus, couldn't find any installed skins. You should try to fix this by going " + "to the settings and selecting your current Steam installation folder.", Margin = new Thickness(10), TextWrapping = TextWrapping.WrapWithOverflow }; _availableSkinsCatalog = new Catalog("skins.xml"); RebuildAvailableTab(); if (invalidSteamLocation) { StackInstalled.Children.Add(invalidSteamLocationWarning); SetInstallControlsEnabledState(false); _lockInstallControlsState = true; } else { RebuildInstalledTab(); } SetOnlineStatus(); CheckBoxRestartSteam.IsChecked = Properties.Settings.Default.RestartSteam; }
private void GetValidWindows(object s) { var processInfoMap = new Dictionary <uint, string>(); try { using (var searcher = new ManagementObjectSearcher("SELECT ProcessId, Name FROM Win32_Process")) using (var results = searcher.Get()) { foreach (var item in results) { var id = item["ProcessID"]; var name = item["Name"] as string; if (name != null) { processInfoMap.Add((uint)id, name); } } } } catch { } // Get valid running windows var windows = SystemWindow.AllToplevelWindows.Where ( w => w.Visible && // Must be a visible windows w.Title != "" && // Must have a window title (w.ExtendedStyle & WindowExStyleFlags.TOOLWINDOW) != WindowExStyleFlags.TOOLWINDOW // Must not be a tool window ); foreach (SystemWindow sWind in windows) { try { string className, title, fileName; SystemWindow realWindow = GestureSign.Common.Applications.ApplicationManager.GetWindowInfo(sWind, out className, out title, out fileName); if ("ApplicationFrameWindow".Equals(className) || realWindow == null) { continue; } var pid = (uint)realWindow.ProcessId; if (!processInfoMap.TryGetValue(pid, out fileName)) { try { fileName = realWindow.Process.MainModule.FileName; } catch { continue; } } BitmapSource iconSource; try { iconSource = Imaging.CreateBitmapSourceFromHIcon(realWindow.Icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); iconSource.Freeze(); } catch { continue; } ApplicationListViewItem lItem = new ApplicationListViewItem { WindowClass = className, WindowTitle = title, WindowFilename = fileName, ApplicationIcon = iconSource }; //lItem.ApplicationName = sWind.Process.MainModule.FileVersionInfo.FileDescription; this.lstRunningApplications.Dispatcher.InvokeAsync(new Action(() => { this.lstRunningApplications.Items.Add(lItem); }), DispatcherPriority.Input); } catch (Exception e) { Logging.LogException(e); } } }
public static BitmapSource GetStockIcon(WindowsUtilities.StockIconId id, WindowsUtilities.SHGSI flags) { return(Imaging.CreateBitmapSourceFromHIcon(WindowsUtilities.GetStockIcon(id, flags).Handle, Int32Rect.Empty, null)); }
private byte[] BytesFromIcon(Icon icon) { return(BytesFromBitmapSource(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()))); }
/// <summary> /// Constructor with parameters</summary> /// <param name="title">Dialog title</param> /// <param name="message">Message text</param> /// <param name="buttons">Specifies the buttons that are displayed on the message box</param> /// <param name="image">Icon that is displayed by the message box</param> public MessageBoxDialog(string title, string message, MessageBoxButton buttons, MessageBoxImage image) : this() { Loaded += new RoutedEventHandler(MessageBoxDialog_Loaded); MessageBoxResult = MessageBoxResult.None; OkButton.Visibility = (buttons == MessageBoxButton.OKCancel || buttons == MessageBoxButton.OK) ? Visibility.Visible : Visibility.Collapsed; YesButton.Visibility = NoButton.Visibility = (buttons == MessageBoxButton.YesNo || buttons == MessageBoxButton.YesNoCancel) ? Visibility.Visible : Visibility.Collapsed; CancelButton.Visibility = (buttons == MessageBoxButton.OKCancel || buttons == MessageBoxButton.YesNoCancel) ? Visibility.Visible : Visibility.Collapsed; if (OkButton.Visibility == System.Windows.Visibility.Visible) { OkButton.IsDefault = true; } else { YesButton.IsDefault = true; } if (message != null) { MessageText.Text = message; } if (title != null) { Title = title; } Icon icon = null; switch (image) { case MessageBoxImage.Error: icon = SystemIcons.Error; break; case MessageBoxImage.Question: icon = SystemIcons.Question; break; case MessageBoxImage.Warning: icon = SystemIcons.Warning; break; case MessageBoxImage.Asterisk: icon = SystemIcons.Asterisk; break; case MessageBoxImage.None: default: break; } if (icon != null) { BitmapSource bs = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); Image.Source = bs; } else { Image.Visibility = Visibility.Collapsed; } }
static BitmapSource IconToImageSourceConverter(Icon icon) { return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
private void Window_Initialized(object sender, EventArgs e) { LoadSettings(); imageWarning.Source = Imaging.CreateBitmapSourceFromHIcon(SystemIcons.Warning.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); }
public static ImageSource GetImage(string key, string path, int iconSize) { // https://github.com/CoenraadS/Windows-Control-Panel-Items/ // https://gist.github.com/jnm2/79ed8330ceb30dea44793e3aa6c03f5b string iconStringRaw = path.Substring(key.Length); var iconString = new List <string>(iconStringRaw.Split(new[] { ',' }, 2)); IntPtr iconPtr = IntPtr.Zero; IntPtr dataFilePointer; IntPtr iconIndex; uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; Logger.WoxTrace($"{nameof(iconStringRaw)}: {iconStringRaw}"); if (string.IsNullOrEmpty(iconString[0])) { var e = new ArgumentException($"iconString empth {path}"); e.Data.Add(nameof(path), path); throw e; } if (iconString[0][0] == '@') { iconString[0] = iconString[0].Substring(1); } dataFilePointer = LoadLibraryEx(iconString[0], IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); if (iconString.Count == 2) { // C:\WINDOWS\system32\mblctr.exe,0 // %SystemRoot%\System32\FirewallControlPanel.dll,-1 var index = Math.Abs(int.Parse(iconString[1])); iconIndex = (IntPtr)index; iconPtr = LoadImage(dataFilePointer, iconIndex, 1, iconSize, iconSize, 0); } if (iconPtr == IntPtr.Zero) { IntPtr defaultIconPtr = IntPtr.Zero; var callback = new EnumResNameDelegate((hModule, lpszType, lpszName, lParam) => { defaultIconPtr = lpszName; return(false); }); var result = EnumResourceNamesWithID(dataFilePointer, GROUP_ICON, callback, IntPtr.Zero); //Iterate through resources. if (!result) { int error = Marshal.GetLastWin32Error(); int userStoppedResourceEnumeration = 0x3B02; if (error != userStoppedResourceEnumeration) { Win32Exception exception = new Win32Exception(error); exception.Data.Add(nameof(path), path); throw exception; } } iconPtr = LoadImage(dataFilePointer, defaultIconPtr, 1, iconSize, iconSize, 0); } FreeLibrary(dataFilePointer); BitmapSource image; if (iconPtr != IntPtr.Zero) { image = Imaging.CreateBitmapSourceFromHIcon(iconPtr, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image.CloneCurrentValue(); //Remove pointer dependancy. image.Freeze(); DestroyIcon(iconPtr); return(image); } else { var e = new ArgumentException($"iconPtr zero {path}"); e.Data.Add(nameof(path), path); throw e; } }
public static ImageSource ExtractIconFromPath(string path) => Imaging.CreateBitmapSourceFromHIcon(ExtractFromPath(path).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
public static async Task <ImageSource> GetIconAsync(string extension, string fullName) { if (iconCache == null) { iconCache = new Dictionary <string, ImageSource>(); } if (folderIconCache == null) { folderIconCache = new Dictionary <int, ImageSource>(); } extension = extension ?? "dir"; // File cache if (iconCache.ContainsKey(extension)) { return(iconCache[extension]); } // Get icon pointer IntPtr handleIcon; int iIcon = 0; if (extension == "dir") { SHFILEINFO shinfo = new SHFILEINFO(); SHGetFileInfo(fullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON); handleIcon = shinfo.hIcon; iIcon = shinfo.iIcon; // Folder icon cache if (folderIconCache.ContainsKey(iIcon)) { return(folderIconCache[iIcon]); } } else { handleIcon = Icon.ExtractAssociatedIcon(fullName).Handle; } ImageSource icon = null; if (handleIcon != IntPtr.Zero) { await Task.Run(() => { icon = Imaging.CreateBitmapSourceFromHIcon(handleIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); icon.Freeze(); }); } DestroyIcon(handleIcon); // Add to cache if (extension == "dir") { folderIconCache.Add(iIcon, icon); } else { if (!cacheExcludedExtensions.Contains(extension)) { iconCache.Add(extension, icon); } } return(icon); }
/// <summary> /// ファイルをドラッグした時のイベントハンドラ /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UserControl_Drop(object sender, DragEventArgs e) { var vm = this.DataContext as FileAccessViewModel; var list = vm.FileInfoList; var pathList = vm.FileInfoList.Select(x => x.FilePath); var DuplicateFilePathList = new List <string>(); if (!(e.Data.GetData(DataFormats.FileDrop) is string[] files)) { return; } foreach (var s in files) { if (pathList.Contains(s)) { DuplicateFilePathList.Add(s); continue; } var fileInfo = new FileInfo { FilePath = s, FileName = System.IO.Path.GetFileName(s) }; if (File.Exists(s)) { var icon = System.Drawing.Icon.ExtractAssociatedIcon(s); fileInfo.Icon = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } else if (Directory.Exists(s)) { var shinfo = new SHFILEINFO(); var hImgSmall = Win32.SHGetFileInfo(s, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); var icon = System.Drawing.Icon.FromHandle(shinfo.hIcon); fileInfo.Icon = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } list.Add(fileInfo); vm.SynchronizeDisplayFileList(); var extension = Path.GetExtension(s); if (!vm.ExtensionList.Select(x => x.Name).Contains(extension)) { Extension addExtension; if (extension == "") { addExtension = new Extension("", "(フォルダ)"); } else { addExtension = new Extension(extension); } vm.ExtensionList.Add(addExtension); } } if (DuplicateFilePathList.Any()) { var message = "下記のアイテムは既に登録済みのため登録されませんでした。\n"; foreach (var item in DuplicateFilePathList) { message += " " + item + "\n"; } MessageBox.Show(message); } WatermarkTextBox.Visibility = vm.FileInfoList.Any() ? Visibility.Collapsed : Visibility.Visible; }
public void CreateMenu() { this.context_menu = new ContextMenu(); this.state_item = new SparkleMenuItem { Header = Controller.StateText, IsEnabled = false }; Image folder_image = new Image { Source = UserInterfaceHelpers.GetImageSource("sparkleshare-folder"), Width = 16, Height = 16 }; SparkleMenuItem folder_item = new SparkleMenuItem { Header = "SparkleShare", Icon = folder_image }; SparkleMenuItem add_item = new SparkleMenuItem { Header = "Add hosted project…" }; this.log_item = new SparkleMenuItem { Header = "Recent changes…", IsEnabled = Controller.RecentEventsItemEnabled }; SparkleMenuItem link_code_item = new SparkleMenuItem { Header = "Client ID" }; if (Controller.LinkCodeItemEnabled) { SparkleMenuItem code_item = new SparkleMenuItem { Header = SparkleShare.Controller.UserAuthenticationInfo.PublicKey.Substring(0, 20) + "..." }; SparkleMenuItem copy_item = new SparkleMenuItem { Header = "Copy to Clipboard" }; copy_item.Click += delegate { Controller.CopyToClipboardClicked(); }; link_code_item.Items.Add(code_item); link_code_item.Items.Add(new Separator()); link_code_item.Items.Add(copy_item); } CheckBox notify_check_box = new CheckBox { Margin = new Thickness(6, 0, 0, 0), IsChecked = SparkleShare.Controller.NotificationsEnabled }; SparkleMenuItem notify_item = new SparkleMenuItem { Header = "Notifications", Icon = notify_check_box }; SparkleMenuItem about_item = new SparkleMenuItem { Header = "About SparkleShare" }; this.exit_item = new SparkleMenuItem { Header = "Exit" }; add_item.Click += delegate { Controller.AddHostedProjectClicked(); }; this.log_item.Click += delegate { Controller.RecentEventsClicked(); }; about_item.Click += delegate { Controller.AboutClicked(); }; notify_check_box.Click += delegate { this.context_menu.IsOpen = false; SparkleShare.Controller.ToggleNotifications(); notify_check_box.IsChecked = SparkleShare.Controller.NotificationsEnabled; }; notify_item.Click += delegate { SparkleShare.Controller.ToggleNotifications(); notify_check_box.IsChecked = SparkleShare.Controller.NotificationsEnabled; }; this.exit_item.Click += delegate { this.notify_icon.Dispose(); Controller.QuitClicked(); }; this.context_menu.Items.Add(this.state_item); this.context_menu.Items.Add(new Separator()); this.context_menu.Items.Add(folder_item); state_menu_items = new SparkleMenuItem[Controller.Projects.Length]; if (Controller.Projects.Length > 0) { int i = 0; foreach (ProjectInfo project in Controller.Projects) { SparkleMenuItem subfolder_item = new SparkleMenuItem { Header = project.Name.Replace("_", "__"), Icon = new Image { Source = UserInterfaceHelpers.GetImageSource("folder"), Width = 16, Height = 16 } }; state_menu_items[i] = new SparkleMenuItem { Header = project.StatusMessage, IsEnabled = false }; subfolder_item.Items.Add(state_menu_items[i]); subfolder_item.Items.Add(new Separator()); SparkleMenuItem open_item = new SparkleMenuItem { Header = "Open folder", Icon = new Image { Source = UserInterfaceHelpers.GetImageSource("folder"), Width = 16, Height = 16 } }; open_item.Click += new RoutedEventHandler(Controller.OpenFolderDelegate(project.Name)); subfolder_item.Items.Add(open_item); subfolder_item.Items.Add(new Separator()); if (project.IsPaused) { SparkleMenuItem resume_item; if (project.UnsyncedChangesInfo.Count > 0) { foreach (KeyValuePair <string, string> pair in project.UnsyncedChangesInfo) { subfolder_item.Items.Add(new SparkleMenuItem { Header = pair.Key, // TODO image IsEnabled = false }); } if (!string.IsNullOrEmpty(project.MoreUnsyncedChanges)) { subfolder_item.Items.Add(new SparkleMenuItem { Header = project.MoreUnsyncedChanges, IsEnabled = false }); } subfolder_item.Items.Add(new Separator()); resume_item = new SparkleMenuItem { Header = "Sync and Resume…" }; } else { resume_item = new SparkleMenuItem { Header = "Resume" }; } resume_item.Click += (sender, e) => Controller.ResumeDelegate(project.Name)(sender, e); subfolder_item.Items.Add(resume_item); } else { if (Controller.Projects[i].HasError) { subfolder_item.Icon = new Image { Source = Imaging.CreateBitmapSourceFromHIcon( Drawing.SystemIcons.Exclamation.Handle, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(16, 16)) }; SparkleMenuItem try_again_item = new SparkleMenuItem { Header = "Retry Sync" }; try_again_item.Click += (sender, e) => Controller.TryAgainDelegate(project.Name)(sender, e); subfolder_item.Items.Add(try_again_item); } else { SparkleMenuItem pause_item = new SparkleMenuItem { Header = "Pause" }; pause_item.Click += (sender, e) => Controller.PauseDelegate(project.Name)(sender, e); subfolder_item.Items.Add(pause_item); } } this.context_menu.Items.Add(subfolder_item); i++; } ; } folder_item.Items.Add(this.log_item); folder_item.Items.Add(add_item); folder_item.Items.Add(new Separator()); folder_item.Items.Add(notify_item); folder_item.Items.Add(new Separator()); folder_item.Items.Add(link_code_item); folder_item.Items.Add(new Separator()); folder_item.Items.Add(about_item); this.context_menu.Items.Add(new Separator()); this.context_menu.Items.Add(this.exit_item); this.notify_icon.ContextMenu = this.context_menu; }
public DialogWindow(Window parent, string message, string title, MessageBoxButton messageBoxButton, MessageBoxImage messageBoxImage) : base() { InitializeComponent(); Closing += new CancelEventHandler(DialogWindow_Closing); Owner = parent; Title = title; LabelContent.Text = message; if (Owner == null) { WindowStartupLocation = WindowStartupLocation.CenterScreen; } if (messageBoxButton == MessageBoxButton.OK || messageBoxButton == MessageBoxButton.OKCancel) { ButtonOk.Visibility = Visibility.Visible; ButtonOk.Click += new RoutedEventHandler(ButtonOk_Click); ButtonOk.Focus(); } if (messageBoxButton == MessageBoxButton.YesNo || messageBoxButton == MessageBoxButton.YesNoCancel) { ButtonYes.Visibility = Visibility.Visible; ButtonNo.Visibility = Visibility.Visible; ButtonNo.Focus(); ButtonYes.Click += new RoutedEventHandler(ButtonYes_Click); ButtonNo.Click += new RoutedEventHandler(ButtonNo_Click); } if (messageBoxButton == MessageBoxButton.OKCancel || messageBoxButton == MessageBoxButton.YesNoCancel) { ButtonCancel.Visibility = Visibility.Visible; ButtonCancel.Focus(); ButtonCancel.Click += new RoutedEventHandler(ButtonCancel_Click); } if (messageBoxImage != MessageBoxImage.None) { Image.Visibility = Visibility.Visible; switch (messageBoxImage) { case MessageBoxImage.Information: Image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Information.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); System.Media.SystemSounds.Asterisk.Play(); break; case MessageBoxImage.Question: Image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Question.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); System.Media.SystemSounds.Question.Play(); break; case MessageBoxImage.Exclamation: Image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Exclamation.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); System.Media.SystemSounds.Exclamation.Play(); break; case MessageBoxImage.Error: Image.Source = Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Error.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); System.Media.SystemSounds.Hand.Play(); break; } } ShowDialog(); }
public static ImageSource GetIcon(string filePath) { ImageSource resultImageSource; var fileInfo = new FileInfo(filePath); var isHidden = ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden); var isSystem = ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System); var isLink = ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint); // Если папка if (!fileInfo.Exists) { resultImageSource = (isHidden || isSystem) ? Table[UcImages.HiddenFolder.ToString()] : Table[UcImages.Folder.ToString()]; if (isLink) { resultImageSource = Table[UcImages.Link.ToString()]; } } else // File { if (isHidden || isSystem) { resultImageSource = Table[UcImages.HiddenFile.ToString()]; return(resultImageSource); } if (isLink) { resultImageSource = Table[UcImages.Link.ToString()]; return(resultImageSource); } var extension = fileInfo.Extension.ToLower(); if (extension != ".exe" && extension != ".lnk") { // Если такой файл мы уже загружали if (Table.ContainsKey(extension)) { resultImageSource = Table[extension]; return(resultImageSource); } using (var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath)) { resultImageSource = Imaging.CreateBitmapSourceFromHIcon( sysicon.Handle, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromWidthAndHeight(ImagePixelSize, ImagePixelSize)); } Table.Add(extension, resultImageSource); } else { //resultImageSource = Table[UcImages.UnknownExe.ToString()]; using (var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath)) { Debug.Assert(sysicon != null, "sysicon != null"); resultImageSource = Imaging.CreateBitmapSourceFromHIcon( sysicon.Handle, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromWidthAndHeight(ImagePixelSize, ImagePixelSize)); } } } return(resultImageSource); }
private static BitmapSource GetIcon(Icon icon) => Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
internal static MessageBoxWindow CreateWindow(string message, string caption, MessageBoxButton button, MessageBoxImage icon, SystemSound sound, Exception exception) { MessageBoxWindow window = null; Application.Current.Dispatcher.Invoke(() => { window = new MessageBoxWindow(); if (Application.Current.MainWindow.IsLoaded) { window.Owner = Application.Current.MainWindow; } window.Title = caption; window.MessageTextBlock.Text = message; window.Buttons = button; switch (button) { case MessageBoxButton.OK: window.OKButton.Visibility = Visibility.Visible; break; case MessageBoxButton.OKCancel: window.OKButton.Visibility = Visibility.Visible; window.CancelButton.Visibility = Visibility.Visible; break; case MessageBoxButton.YesNo: window.YesButton.Visibility = Visibility.Visible; window.NoButton.Visibility = Visibility.Visible; break; case MessageBoxButton.YesNoCancel: window.YesButton.Visibility = Visibility.Visible; window.NoButton.Visibility = Visibility.Visible; window.CancelButton.Visibility = Visibility.Visible; break; } var iconHandle = IntPtr.Zero; switch (icon) { case MessageBoxImage.Hand: iconHandle = SystemIcons.Hand.Handle; break; case MessageBoxImage.Question: iconHandle = SystemIcons.Question.Handle; break; case MessageBoxImage.Exclamation: iconHandle = SystemIcons.Exclamation.Handle; break; case MessageBoxImage.Asterisk: iconHandle = SystemIcons.Asterisk.Handle; break; } if (iconHandle != IntPtr.Zero) { window.IconImage.Source = Imaging.CreateBitmapSourceFromHIcon(iconHandle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); window.IconImage.Visibility = Visibility.Visible; } if (exception != null) { window.ShowExceptionExpander(exception); } window.Sound = sound; }); return(window); }
private static BitmapSource GetFileIcon(string filePath) { var icon = Icon.ExtractAssociatedIcon(filePath); return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
public static List <TrayIconInfo> List() { if (!_initialized) { Init(); } List <TrayIconInfo> retval = new List <TrayIconInfo>(); // btnPtr: this is a pointer sized remote buffer that we can pass to send message, which will put the btn address in it // btn: the remote btn object // reader: use to read remote data using (RemoteProcBuffer btnPtr = new RemoteProcBuffer(explorerPid, (uint)UIntPtr.Size)) using (RemoteProcBuffer btn = new RemoteProcBuffer(explorerPid, (uint)Math.Max(Marshal.SizeOf(typeof(Win32.Structs.TBBUTTONx64)), Marshal.SizeOf(typeof(Win32.Structs.TBBUTTONx86))))) using (RemoteProcReader reader = new RemoteProcReader(explorerPid)) { int iconCount = (int)Win32.SendMessage(iconWindow, Win32.Constants.TB_BUTTONCOUNT, IntPtr.Zero, IntPtr.Zero); for (int i = 0; i < iconCount; ++i) { // Get address of btn struct Win32.SendMessage(iconWindow, Win32.Constants.TB_GETBUTTON, (IntPtr)i, (IntPtr)(long)btnPtr.BufAddr); // Now get the string address, trayData and whether it's hidden UIntPtr iString; bool isHidden; Win32.Structs.TRAYDATA trayData; if (IntPtr.Size == 8) // We need a separate struct for each bitness { Win32.Structs.TBBUTTONx64 btnObj = reader.ReadObj <Win32.Structs.TBBUTTONx64>(btnPtr.BufAddr); iString = btnObj.iString; isHidden = (btnObj.fsState & Win32.Constants.TBSTATE_HIDDEN) != 0; trayData = reader.ReadObj <Win32.Structs.TRAYDATA>(btnObj.dwData); } else { Win32.Structs.TBBUTTONx86 btnObj = reader.ReadObj <Win32.Structs.TBBUTTONx86>(btnPtr.BufAddr); iString = btnObj.iString; isHidden = (btnObj.fsState & Win32.Constants.TBSTATE_HIDDEN) != 0; trayData = reader.ReadObj <Win32.Structs.TRAYDATA>(btnObj.dwData); } int ret = Win32.GetWindowThreadProcessId(trayData.hwnd, out int iconPid); Win32.ThrowOnError(ret == 0, Marshal.GetLastWin32Error(), "GetWindowThreadProcessId for icon"); string fileName; BitmapSource bitmap = null; try { fileName = Process.GetProcessById(iconPid).MainModule.FileName; try { bitmap = Imaging.CreateBitmapSourceFromHIcon((IntPtr)(long)trayData.hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch { } // err, do something, but what? } catch (Exception e) { fileName = $"error [{e.Message}]"; } // Get the tool tip, one char at a time List <char> tooTipCharList = new List <char>(); short c; // Use short, so the size is 2 bytes, since it's a wide char while ((c = reader.ReadObj <short>((UIntPtr)((uint)iString + (tooTipCharList.Count * Marshal.SizeOf(typeof(short)))))) != '\0') { tooTipCharList.Add((char)c); } retval.Add(new TrayIconInfo { FileName = fileName, PID = iconPid, Bitmap = bitmap, IsHidden = isHidden, ToolTip = new string(tooTipCharList.ToArray()) }); } } return(retval); }
public static ImageSource ExtractIcon(string fileName, int id) { IntPtr hIcon = ExtractIcon(Process.GetCurrentProcess().Handle, fileName, id); return(Imaging.CreateBitmapSourceFromHIcon(hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
public static ImageSource ToImageSource(this Icon icon) { return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
/// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> private static BitmapSource GetIconFromPath(string path = "", bool defaultIfNotFound = false) { //TODO: check for thread concurrency issues BitmapSource bitmap; if (!procIconLst.TryGetValue(path, out bitmap)) { Icon ic = null; switch (path) { case "System": ic = SystemIcons.WinLogo; break; case "-": ic = SystemIcons.WinLogo; break; case "": case "?error": //FIXME: Use something else? case "Unknown": ic = SystemIcons.Error; break; default: // Using FileHelper.GetFriendlyPath(path) to cover paths like \device\harddiskvolume1\program files etc. string friendlyPath = FileHelper.GetFriendlyPath(path); if (!path.Contains("\\")) { LogHelper.Debug($"Skipped extract icon: '{friendlyPath}' because path has no directory info."); break; } try { ic = Icon.ExtractAssociatedIcon(friendlyPath) ?? (defaultIfNotFound ? SystemIcons.Application : null); } catch (ArgumentException) { LogHelper.Debug("Unable to extract icon: " + friendlyPath + (!friendlyPath.Equals(path) ? " (" + path + ")" : "")); ic = SystemIcons.Question; //FIXME: Use some generic application icon? } catch (System.IO.FileNotFoundException) //Undocumented exception { LogHelper.Debug("Unable to extract icon: " + friendlyPath + (!friendlyPath.Equals(path) ? " (" + path + ")" : "")); ic = SystemIcons.Warning; } break; } if (ic != null) { //FIXME: Resize the icon to save some memory? bitmap = Imaging.CreateBitmapSourceFromHIcon(ic.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bitmap.Freeze(); ic.Dispose(); lock (procIconLstLocker) procIconLst.TryAdd(path, bitmap); } } return(bitmap); }
internal static ImageSource CreateFromIcon(Icon icon) { return(Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
private static Bitmap ExtractIcon(Icon icon) { var bitmapSource = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return(ToBitmap(bitmapSource)); }