Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
glebov21 committed Oct 9, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 544cd31 commit c415093
Showing 26 changed files with 1,144 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/.vs
/bin
/obj
/packages
/publish
/NewPMSetup.exe
*.csproj.user
6 changes: 6 additions & 0 deletions App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
9 changes: 9 additions & 0 deletions App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="NewProcessMonitoring.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:NewProcessMonitoring"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
17 changes: 17 additions & 0 deletions App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace NewProcessMonitoring
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
15 changes: 15 additions & 0 deletions MainWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Window x:Class="NewProcessMonitoring.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:NewProcessMonitoring"
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">
<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>
</Window>
149 changes: 149 additions & 0 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NewProcessMonitoring
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private int _watchProcessTimeoutMs = 5000;

private ObservableCollection<ProcessTableItem> _tableItems = new ObservableCollection<ProcessTableItem>();
private ProcessFileWorker _processFileWorker = new ProcessFileWorker(System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NewPm", "processes.json"));

private SemaphoreSlim _tableItemsRefreshSemaphore = new SemaphoreSlim(1);

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

public MainWindow()
{
InitializeComponent();

MinimizeToTray.Enable(this);

tProcesses.ItemsSource = _tableItems;

_ = ProcessWatcherLoopAsync();
}


public async Task ProcessWatcherLoopAsync()
{

var newTableItems = new List<ProcessTableItem>();
while (true)
{
await Task.Delay(_watchProcessTimeoutMs);
if (!this.IsActive) //watch only if background
await RefreshProcessTableAsync();
}
}

private async Task RefreshProcessTableAsync()
{
await _tableItemsRefreshSemaphore.WaitAsync();

Debug.WriteLine("Refresh table");

var newTableItems = new Dictionary<string, ProcessTableItem>();

using (var results = processSearcher.Get())
{
foreach (var mo in results.Cast<ManagementObject>())
{
var pTitle = (string)mo["Caption"];
var pPath = (string)mo["ExecutablePath"];
var pCommandLine = (string)mo["CommandLine"];
if (!string.IsNullOrEmpty(pPath))
{
if (!_processFileWorker.ItemsByFullPath.ContainsKey(pPath))
newTableItems[pPath] = new ProcessTableItem(pTitle, pPath, DateTime.Now);
}
}
}


//Fill table with untrusted items
_tableItems.Clear();
foreach(var newItem in newTableItems.Values)
_tableItems.Add(newItem);
foreach (var untrustedItem in _processFileWorker.ItemsByFullPath.Values.Where(x => !x.IsTrusted))
_tableItems.Add(new ProcessTableItem(untrustedItem.Title, untrustedItem.FullPath, untrustedItem.FirstFoundUtcDate));

//Add new untrusted items to file
_processFileWorker.TryAddNewProcess(newTableItems.Values.Select(x => new ProcessFileItem(x.Name, x.FullPath, x.FirstFoundLocalDate.ToUniversalTime(), false)));

//Order by alph:
var ordered = _tableItems.OrderBy(x => x.Name).ToList();

_tableItems.Clear();
foreach (var item in ordered)
_tableItems.Add(item);

_tableItemsRefreshSemaphore.Release();
}


private void bnApplyAllToTrusted_Click(object sender, RoutedEventArgs e)
{
_tableItemsRefreshSemaphore.Wait();
_processFileWorker.TryAddNewProcess(_tableItems.Select(x => new ProcessFileItem(x.Name, x.FullPath, x.FirstFoundLocalDate.ToUniversalTime(), true)));
_tableItemsRefreshSemaphore.Release();

_ = RefreshProcessTableAsync();
}

//private void bnClose_Click(object sender, RoutedEventArgs e)
//{
// this.Close();
//}

private void bnClearTrustList_Click(object sender, RoutedEventArgs e)
{
_processFileWorker.ClearAllAddedProcesses();
_ = RefreshProcessTableAsync();
}

private void wMain_Activated(object sender, EventArgs e)
{
_ = RefreshProcessTableAsync(); //Force refresh
}

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";
}

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.WindowState = WindowState.Minimized;
e.Cancel = true;
}

private void Window_SourceInitialized(object sender, EventArgs e)
{
WindowExtensions.HideMinimizeAndMaximizeButtons(this);
this.WindowState = WindowState.Minimized;
}
}
}
99 changes: 99 additions & 0 deletions MinimizeToTray.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace NewProcessMonitoring
{
internal class MinimizeToTray
{
/// <summary>
/// Enables "minimize to tray" behavior for the specified Window.
/// </summary>
/// <param name="window">Window to enable the behavior for.</param>
public static void Enable(Window window)
{
// No need to track this instance; its event handlers will keep it alive
new MinimizeToTrayInstance(window);
}

/// <summary>
/// Class implementing "minimize to tray" functionality for a Window instance.
/// </summary>
private class MinimizeToTrayInstance
{
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)
{
Debug.Assert(window != null, "window parameter is null.");
_window = window;
_window.StateChanged += HandleStateChanged;
}

/// <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();


_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();
}
}
}
}
109 changes: 109 additions & 0 deletions NSIS_SetupFile.nsi
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
;NSIS Modern User Interface
;Basic Example Script
;Written by Joost Verburg

;--------------------------------
;Include Modern UI

!include "MUI2.nsh"

;--------------------------------
;General

;Name and file
Name "New Process Monitoring"
OutFile "NewPMSetup.exe"
Unicode True

;Default installation folder
InstallDir "$LOCALAPPDATA\NewPm"

;Get installation folder from registry if available
InstallDirRegKey HKCU "Software\NewPm" ""

;Request application privileges for Windows Vista
RequestExecutionLevel user

;--------------------------------
;Interface Settings

!define MUI_ABORTWARNING

;--------------------------------
;Pages

; !insertmacro MUI_PAGE_LICENSE "${NSISDIR}\Docs\Modern UI\License.txt"
; !insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES

!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES

;--------------------------------
;Languages

!insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Installer Sections

Section "Dummy Section" SecDummy

SetOutPath "$INSTDIR"

;ADD YOUR OWN FILES HERE...
File /r "bin\Release\*"

;Store installation folder
WriteRegStr HKCU "Software\NewPm" "" $INSTDIR

;Autorun
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "NewPm" "$InstDir\NewProcessMonitoring.exe"

;Shortcut
CreateDirectory "$SMPrograms\NewPm"
CreateShortcut "$SMPrograms\NewPm\NewPm.lnk" "$InstDir\NewProcessMonitoring.exe"

;Create uninstaller
WriteUninstaller "$INSTDIR\Uninstall.exe"
CreateShortcut "$SMPrograms\NewPm\Uninstall NewPm.lnk" "$InstDir\Uninstall.exe"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\NewPm" \
"DisplayName" "New Process Monitoring Tool"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\NewPm" \
"UninstallString" "$\"$INSTDIR\Uninstall.exe$\""

System::Call 'shell32.dll::SHChangeNotify(i, i, i, i) v (0x08000000, 0, 0, 0)'
Exec '"$WINDIR\explorer.exe" "$InstDir\NewProcessMonitoring.exe"'
SectionEnd

;--------------------------------
;Descriptions

;Language strings
LangString DESC_SecDummy ${LANG_RUSSIAN} "A test section."

;Assign language strings to sections
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SecDummy} $(DESC_SecDummy)
!insertmacro MUI_FUNCTION_DESCRIPTION_END

;--------------------------------
;Uninstaller Section

Section "Uninstall"

;ADD YOUR OWN FILES HERE...

Delete "$INSTDIR\Uninstall.exe"

RMDir /r "$INSTDIR"

Delete "$SMPrograms\NewPm\NewPm.lnk"
Delete "$SMPrograms\NewPm\Uninstall NewPm.lnk"

DeleteRegKey /ifempty HKCU "Software\NewPm"
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "NewPm"
DeleteRegKey HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\NewPm"

SectionEnd
25 changes: 25 additions & 0 deletions NewProcessMonitoring.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35219.272
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NewProcessMonitoringNetFwk", "NewProcessMonitoringNetFwk.csproj", "{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A4C0AA2-336A-4293-813E-B27ABFD7DE4C}
EndGlobalSection
EndGlobal
172 changes: 172 additions & 0 deletions NewProcessMonitoringNetFwk.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0A6C6E8A-89DA-49F3-BFE5-EE892B9011D3}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>NewProcessMonitoring</RootNamespace>
<AssemblyName>NewProcessMonitoring</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>1</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>x64</PlatformTarget>
<DebugType>embedded</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>D8BB264147EA066A8B12C5F9F257EEE59C0893BB</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>NewProcessMonitoringNetFwk_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>icon48t.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.CodeDom, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.CodeDom.8.0.0\lib\net462\System.CodeDom.dll</HintPath>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="WindowExtensions.cs" />
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="MinimizeToTray.cs" />
<Compile Include="ProcessFileItem.cs" />
<Compile Include="ProcessFileWorker.cs" />
<Compile Include="ProcessTableItem.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="app.manifest" />
<None Include="NSIS_SetupFile.nsi" />
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<Resource Include="icon.jpg" />
<Resource Include="icon32t.ico" />
<Resource Include="icon48t.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.8 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
20 changes: 20 additions & 0 deletions ProcessFileItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;

namespace NewProcessMonitoring
{
internal class ProcessFileItem
{
public string Title { get; set; }
public string FullPath { get; set; }
public DateTime FirstFoundUtcDate { get; set; }
public bool IsTrusted;

public ProcessFileItem(string title, string fullPath, DateTime firstFoundUtcDate, bool isTrusted)
{
Title = title;
FullPath = fullPath;
FirstFoundUtcDate = firstFoundUtcDate;
IsTrusted = isTrusted;
}
}
}
107 changes: 107 additions & 0 deletions ProcessFileWorker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewProcessMonitoring
{
internal class ProcessFileWorker
{
public readonly string _filePath = string.Empty;
public Dictionary<string, ProcessFileItem> ItemsByFullPath { get; private set; } = new Dictionary<string, ProcessFileItem>();
public ProcessFileWorker(string logFilePath)
{
if (string.IsNullOrEmpty(logFilePath))
throw new ArgumentNullException(nameof(logFilePath));

Debug.WriteLine($"Process file: {logFilePath}");
_filePath = logFilePath;
CheckDir();

LoadFromFile();
}



public void ClearAllAddedProcesses()
{
ItemsByFullPath.Clear();
Save();
}

public void TryAddNewProcess(IEnumerable<ProcessFileItem> logItems)
{
bool isNeedSave = false;

foreach (var logItem in logItems)
{
if (ItemsByFullPath.TryGetValue(logItem.FullPath, out ProcessFileItem existItem))
{
if (existItem?.IsTrusted != logItem.IsTrusted)
{
ItemsByFullPath[logItem.FullPath] = logItem;
isNeedSave = true;
}
}
else
{
ItemsByFullPath.Add(logItem.FullPath, logItem);
isNeedSave = true;
}
}

if(isNeedSave)
this.Save();
}

public void SetProcessToTrusted()
{
File.WriteAllText(_filePath, string.Empty); //already check for exists
}

public void Save()
{
Debug.WriteLine("Save file");
var json = JsonConvert.SerializeObject(ItemsByFullPath.Values.ToList());
File.WriteAllText(_filePath, json); //already check for exists
}

private void LoadFromFile()
{
ItemsByFullPath.Clear();
if (File.Exists(_filePath))
{
var json = File.ReadAllText(_filePath);
if (!string.IsNullOrWhiteSpace(json))
{
try
{
var deserializedItems = JsonConvert.DeserializeObject<List<ProcessFileItem>>(json);
if (deserializedItems != null)
{
foreach (var item in deserializedItems) {
ItemsByFullPath.Add(item.FullPath, item);
}
}
}
catch {
File.Delete(_filePath); //remove if can't deserialize
}
}
}
}
private void CheckDir()
{
var fileDir = Path.GetDirectoryName(_filePath);
if (fileDir != null)
{
if (!Directory.Exists(fileDir))
Directory.CreateDirectory(fileDir);
}
}
}
}
22 changes: 22 additions & 0 deletions ProcessTableItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewProcessMonitoring
{
internal class ProcessTableItem
{
public ProcessTableItem(string name, string fullPath, DateTime firstFoundLocalDate)
{
Name = name;
FullPath = fullPath;
FirstFoundLocalDate = firstFoundLocalDate;
}

public string Name { get; set; }
public string FullPath { get; set; }
public DateTime FirstFoundLocalDate { get; set; }
};
}
52 changes: 52 additions & 0 deletions Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NewProcessMonitoring")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Evgeny Glebov")]
[assembly: AssemblyProduct("NewProcessMonitoring")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.

//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]


[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]


// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
63 changes: 63 additions & 0 deletions Properties/Resources.Designer.cs
117 changes: 117 additions & 0 deletions Properties/Resources.resx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
26 changes: 26 additions & 0 deletions Properties/Settings.Designer.cs
7 changes: 7 additions & 0 deletions Properties/Settings.settings
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
# NewProcessMonitoring
Monitoring tool for finding new processes and running applications in system

![](Screenshot.png "Screenshot")

This window show all processes what you not added to `Trusted`
Click `Trust All` if this list is OK. This processes will be added to ignore list.
Click `Reset trust list` if you want to see agan full list

## Create setup
1) Open `NSIS_SetupFile.nsi` in NSIS Compiler
2) Click `Compile`
3) Get NewPMSetup.exe from project folder
Binary file added Screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions WindowExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace NewProcessMonitoring
{
internal static class WindowExtensions
{
// from winuser.h
private const int GWL_STYLE = -16,
WS_MAXIMIZEBOX = 0x10000,
WS_MINIMIZEBOX = 0x20000;

[DllImport("user32.dll")]
extern private static int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll")]
extern private static int SetWindowLong(IntPtr hwnd, int index, int value);

internal static void HideMinimizeAndMaximizeButtons(this Window window)
{
IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(window).Handle;
var currentStyle = GetWindowLong(hwnd, GWL_STYLE);

SetWindowLong(hwnd, GWL_STYLE, (currentStyle & ~WS_MAXIMIZEBOX & ~WS_MINIMIZEBOX));
}
}
}
73 changes: 73 additions & 0 deletions app.manifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
<applicationRequestMinimum>
<PermissionSet Unrestricted="true" ID="Custom" SameSite="site" />
<defaultAssemblyRequest permissionSetReference="Custom" />
</applicationRequestMinimum>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
</application>
</compatibility>
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config.
Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
-->
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
Binary file added icon.jpg
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 icon32t.ico
Binary file not shown.
Binary file added icon48t.ico
Binary file not shown.
6 changes: 6 additions & 0 deletions packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
<package id="System.CodeDom" version="8.0.0" targetFramework="net48" />
<package id="System.Management" version="8.0.0" targetFramework="net48" />
</packages>

0 comments on commit c415093

Please sign in to comment.