Skip to content

Commit

Permalink
Open foder, find app in google,
Browse files Browse the repository at this point in the history
fix: tray icon not hide after app close
  • Loading branch information
glebov21 committed Oct 10, 2024
1 parent 1164209 commit 0c8777c
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 75 deletions.
Binary file added Assets/FolderOpened.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/WebBrowser.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
mc:Ignorable="d"
Title="New Process Monitoring" Height="269" Width="561" Activated="wMain_Activated" Closing="Window_Closing" ResizeMode="CanResizeWithGrip" SourceInitialized="Window_SourceInitialized">
<Grid Margin="0,0,0,0">
<DataGrid HeadersVisibility="Column" x:Name="tProcesses" d:ItemsSource="{d:SampleData ItemCount=5}" Margin="10,10,110,10" AutoGeneratingColumn="tProcesses_AutoGeneratingColumn" />
<Button x:Name="bnApplyAllToTrusted" Content="Trust all" HorizontalAlignment="Right" Margin="0,10,10,0" VerticalAlignment="Top" Width="90" Click="bnApplyAllToTrusted_Click"/>
<DataGrid x:Name="tProcesses" d:ItemsSource="{d:SampleData ItemCount=5}" Margin="10,10,110,10" AutoGeneratingColumn="tProcesses_AutoGeneratingColumn"/>
<Button x:Name="bnClearTrustList" Content="Reset trust list" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom" Width="90" Click="bnClearTrustList_Click"/>

</Grid>
Expand Down
56 changes: 52 additions & 4 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
Expand Down Expand Up @@ -31,21 +32,63 @@ public partial class MainWindow : Window
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NewPm", "processes.json"));

private SemaphoreSlim _tableItemsRefreshSemaphore = new SemaphoreSlim(1);
private MinimizeToTray _minimizeToTray;

ManagementObjectSearcher processSearcher = new ManagementObjectSearcher("SELECT ProcessId, Caption, ExecutablePath, CommandLine FROM Win32_Process");

public MainWindow()
{
InitializeComponent();
_minimizeToTray = new MinimizeToTray(this);

MinimizeToTray.Enable(this);
var tbnOpenGoogle = new FrameworkElementFactory(typeof(Image));
var tbnOpenFolder = new FrameworkElementFactory(typeof(Image));

BitmapImage tbnOpenGoogleImage = new BitmapImage(new Uri("pack://application:,,,/Assets/WebBrowser.png"));
tbnOpenGoogle.SetValue(Image.SourceProperty, tbnOpenGoogleImage);

BitmapImage tbnOpenFolderImage = new BitmapImage(new Uri("pack://application:,,,/Assets/FolderOpened.png"));
tbnOpenFolder.SetValue(Image.SourceProperty, tbnOpenFolderImage);

tbnOpenGoogle.AddHandler(Image.MouseUpEvent, new MouseButtonEventHandler((s, e) =>
{
if (tProcesses.SelectedItem != null)
{
var path = ((ProcessTableItem)tProcesses.SelectedItem).FullPath;
var fileName = System.IO.Path.GetFileName(path);
System.Diagnostics.Process.Start("https://www.google.com/search?q=What+is+" + fileName);
}
}));
tbnOpenFolder.AddHandler(Image.MouseUpEvent, new MouseButtonEventHandler((s, e) =>
{
if (tProcesses.SelectedItem != null)
{
var filePath = ((ProcessTableItem)tProcesses.SelectedItem).FullPath;
Process.Start("explorer.exe", "/select, \"" + filePath + "\"");
}
}));

this.tProcesses.Columns.Insert(0, new DataGridTemplateColumn()
{
Header = "",
CellTemplate = new DataTemplate() { VisualTree = tbnOpenGoogle }
}
);
this.tProcesses.Columns.Insert(0, new DataGridTemplateColumn()
{
Header = "",
CellTemplate = new DataTemplate() { VisualTree = tbnOpenFolder }
}
);

tProcesses.ItemsSource = _tableItems;



_ = ProcessWatcherLoopAsync();
Application.Current.Exit += App_Exit;
}


public async Task ProcessWatcherLoopAsync()
{

Expand All @@ -68,8 +111,9 @@ private async Task RefreshProcessTableAsync()

using (var results = processSearcher.Get())
{
foreach (var mo in results.Cast<ManagementObject>())
foreach (var resultItem in results)
{
var mo = (ManagementObject)resultItem;
var pTitle = (string)mo["Caption"];
var pPath = (string)mo["ExecutablePath"];
var pCommandLine = (string)mo["CommandLine"];
Expand Down Expand Up @@ -131,7 +175,7 @@ private void wMain_Activated(object sender, EventArgs e)
private void tProcesses_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(System.DateTime))
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd.MM.yyyy hh.mm";
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd.MM.yyyy hh:mm";
}

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
Expand All @@ -145,5 +189,9 @@ private void Window_SourceInitialized(object sender, EventArgs e)
WindowExtensions.HideMinimizeAndMaximizeButtons(this);
this.WindowState = WindowState.Minimized;
}
private void App_Exit(object sender, ExitEventArgs e)
{
_minimizeToTray.Dispose();
}
}
}
144 changes: 77 additions & 67 deletions MinimizeToTray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,89 +11,99 @@

namespace NewProcessMonitoring
{
internal class MinimizeToTray
internal class MinimizeToTray: IDisposable
{
private Window _window;
private NotifyIcon _notifyIcon;
//private bool _balloonShown;

/// <summary>
/// Enables "minimize to tray" behavior for the specified Window.
/// Initializes a new instance of the MinimizeToTray class.
/// </summary>
/// <param name="window">Window to enable the behavior for.</param>
public static void Enable(Window window)
/// <param name="window">Window instance to attach to.</param>
public MinimizeToTray(Window window)
{
// No need to track this instance; its event handlers will keep it alive
new MinimizeToTrayInstance(window);
Debug.Assert(window != null, "window parameter is null.");
_window = window;
_window.StateChanged += HandleStateChanged;
}

/// <summary>
/// Class implementing "minimize to tray" functionality for a Window instance.
/// Handles the Window's StateChanged event.
/// </summary>
private class MinimizeToTrayInstance
/// <param name="sender">Event source.</param>
/// <param name="e">Event arguments.</param>
private void HandleStateChanged(object sender, EventArgs e)
{
private Window _window;
private NotifyIcon _notifyIcon;
//private bool _balloonShown;

/// <summary>
/// Initializes a new instance of the MinimizeToTrayInstance class.
/// </summary>
/// <param name="window">Window instance to attach to.</param>
public MinimizeToTrayInstance(Window window)
if (_notifyIcon == null)
{
Debug.Assert(window != null, "window parameter is null.");
_window = window;
_window.StateChanged += HandleStateChanged;
// Initialize NotifyIcon instance "on demand"
var contextMenu = new System.Windows.Forms.ContextMenu();
var menuItem_Exit = new System.Windows.Forms.MenuItem();
contextMenu.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] { menuItem_Exit });
menuItem_Exit.Index = 0;
menuItem_Exit.Text = "E&xit";
menuItem_Exit.Click += (_sender, _e) => System.Windows.Application.Current.Shutdown();


_notifyIcon = new NotifyIcon();
_notifyIcon.ContextMenu = contextMenu;
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);
_notifyIcon.MouseClick += new MouseEventHandler(HandleNotifyIconOrBalloonClicked);
_notifyIcon.BalloonTipClicked += new EventHandler(HandleNotifyIconOrBalloonClicked);
}
// Update copy of Window Title in case it has changed
_notifyIcon.Text = _window.Title;

/// <summary>
/// Handles the Window's StateChanged event.
/// </summary>
/// <param name="sender">Event source.</param>
/// <param name="e">Event arguments.</param>
private void HandleStateChanged(object sender, EventArgs e)
{
if (_notifyIcon == null)
{
// Initialize NotifyIcon instance "on demand"
var contextMenu = new System.Windows.Forms.ContextMenu();
var menuItem_Exit = new System.Windows.Forms.MenuItem();
contextMenu.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] { menuItem_Exit });
menuItem_Exit.Index = 0;
menuItem_Exit.Text = "E&xit";
menuItem_Exit.Click += (_sender, _e) => System.Windows.Application.Current.Shutdown();
// Show/hide Window and NotifyIcon
var minimized = (_window.WindowState == WindowState.Minimized);
_window.ShowInTaskbar = !minimized;
_notifyIcon.Visible = minimized;
//if (minimized && !_balloonShown)
//{
// // If this is the first time minimizing to the tray, show the user what happened
// _notifyIcon.ShowBalloonTip(1000, null, _window.Title, ToolTipIcon.None);
// _balloonShown = true;
//}
}

/// <summary>
/// Handles a click on the notify icon or its balloon.
/// </summary>
/// <param name="sender">Event source.</param>
/// <param name="e">Event arguments.</param>
private void HandleNotifyIconOrBalloonClicked(object sender, EventArgs e)
{
// Restore the Window
_window.WindowState = WindowState.Normal;
_window.Activate();
}

_notifyIcon = new NotifyIcon();
_notifyIcon.ContextMenu = contextMenu;
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);
_notifyIcon.MouseClick += new MouseEventHandler(HandleNotifyIconOrBalloonClicked);
_notifyIcon.BalloonTipClicked += new EventHandler(HandleNotifyIconOrBalloonClicked);
}
// Update copy of Window Title in case it has changed
_notifyIcon.Text = _window.Title;

// Show/hide Window and NotifyIcon
var minimized = (_window.WindowState == WindowState.Minimized);
_window.ShowInTaskbar = !minimized;
_notifyIcon.Visible = minimized;
//if (minimized && !_balloonShown)
//{
// // If this is the first time minimizing to the tray, show the user what happened
// _notifyIcon.ShowBalloonTip(1000, null, _window.Title, ToolTipIcon.None);
// _balloonShown = true;
//}
}

/// <summary>
/// Handles a click on the notify icon or its balloon.
/// </summary>
/// <param name="sender">Event source.</param>
/// <param name="e">Event arguments.</param>
private void HandleNotifyIconOrBalloonClicked(object sender, EventArgs e)
{
// Restore the Window
_window.WindowState = WindowState.Normal;
_window.Activate();
}
bool disposed = false;
~MinimizeToTray()
{
Dispose(disposing: false);
}

public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;

_notifyIcon.Visible = false;
_notifyIcon.Icon = null;
_notifyIcon.Dispose();
_notifyIcon = null;

disposed = true;
}
}
}
12 changes: 9 additions & 3 deletions NewProcessMonitoringNetFwk.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,9 @@
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<Resource Include="icon.jpg" />
<Resource Include="icon32t.ico" />
<Resource Include="icon48t.ico" />
<None Include="icon.jpg" />
<None Include="icon32t.ico" />
<None Include="icon48t.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
Expand All @@ -168,5 +168,11 @@
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\FolderOpened.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\WebBrowser.png" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
Binary file modified Screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 0c8777c

Please sign in to comment.