Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for monitorclipboard.cs

(view source code of monitorclipboard.cs as plain text)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Management;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Versioning;
  11. using System.Text;
  12. using System.Windows.Forms;
  13. using Microsoft.Office.Core;
  14. using Microsoft.Win32;
  15. using Excel = Microsoft.Office.Interop.Excel;
  16. using PowerPoint = Microsoft.Office.Interop.PowerPoint;
  17. using Word = Microsoft.Office.Interop.Word;
  18. using Microsoft.Web.WebView2.Core;
  19. using System.Runtime.InteropServices.ComTypes;
  20.  
  21.  
  22. namespace RobvanderWoude
  23. {
  24. 	public partial class FormMonitorClipboard : Form
  25. 	{
  26. 		static readonly string progver = "4.00";
  27.  
  28.  
  29. 		#region Global Variables
  30.  
  31. 		static string clipboardtext = string.Empty;
  32. 		static string gsexec = string.Empty;
  33. 		static readonly string title = string.Format( "MonitorClipboard, Version {0}", progver );
  34. 		static string errormessage = string.Empty;
  35. 		static bool debugmode = false;
  36. 		static bool modalwindow = true;
  37. 		static bool compactmode = false;
  38. 		static float fontsizefactor = 1F;
  39. 		static int interval = 1;
  40. 		static int[] highestversion = new int[] { 0, 0, 0, 0 };
  41. 		static readonly bool isExcelInstalled = ( Type.GetTypeFromProgID( "Excel.Application" ) != null );
  42. 		static readonly bool isGhostScriptInstalled = CheckIfGhostScriptIsInstalled( );
  43. 		static readonly bool isPowerPointInstalled = ( Type.GetTypeFromProgID( "PowerPoint.Application" ) != null );
  44. 		static readonly bool isWordInstalled = ( Type.GetTypeFromProgID( "Word.Application" ) != null );
  45. 		static bool isRedirected = false;
  46. 		static List<string> tempfiles = new List<string>( );
  47. 		static List<string> tempdirs = new List<string>( );
  48.  
  49. 		#endregion Global Variables
  50.  
  51.  
  52. 		public FormMonitorClipboard( )
  53. 		{
  54. 			InitializeComponent( );
  55. 			// Code to hide menu bar in WebViw2 by jpine
  56. 			// https://stackoverflow.com/a/74018241
  57. 			webView2ClipboardContent.CoreWebView2InitializationCompleted += ( sender, e ) =>
  58. 			{
  59. 				if ( e.IsSuccess )
  60. 				{
  61. 					webView2ClipboardContent.CoreWebView2.Settings.HiddenPdfToolbarItems =
  62. 						CoreWebView2PdfToolbarItems.Bookmarks
  63. 						| CoreWebView2PdfToolbarItems.FitPage
  64. 						| CoreWebView2PdfToolbarItems.PageLayout
  65. 						| CoreWebView2PdfToolbarItems.PageSelector
  66. 						| CoreWebView2PdfToolbarItems.Print
  67. 						| CoreWebView2PdfToolbarItems.Rotate
  68. 						| CoreWebView2PdfToolbarItems.Save
  69. 						| CoreWebView2PdfToolbarItems.SaveAs
  70. 						| CoreWebView2PdfToolbarItems.Search
  71. 						| CoreWebView2PdfToolbarItems.ZoomIn
  72. 						| CoreWebView2PdfToolbarItems.ZoomOut;
  73. 				}
  74. 			};
  75. 		}
  76.  
  77.  
  78. 		private void FormMonitorClipboard_Load( object sender, EventArgs e )
  79. 		{
  80. 			// https://www.csharp411.com/console-output-from-winforms-application/
  81. 			// redirect console output to parent process;
  82. 			// must be before any calls to Console.WriteLine( )
  83. 			AttachConsole( ATTACH_PARENT_PROCESS );
  84. 			Text = title;
  85. 			ParseCommandLine( );
  86. 			if ( debugmode )
  87. 			{
  88. 				DebugInfo( );
  89. 				modalwindow = false;
  90. 			}
  91. 			if ( compactmode )
  92. 			{
  93. 				CompactWindow( );
  94. 			}
  95. 			CheckClipboard( );
  96. 			TopMost = modalwindow;
  97. 			ClipboardNotification.ClipboardUpdate += ClipboardNotification_ClipboardUpdate;
  98. 		}
  99.  
  100.  
  101. 		private void ChangeViewerType( ViewerType viewerwindow )
  102. 		{
  103. 			pictureBoxClipboardContent.Visible = ( viewerwindow == ViewerType.Picture );
  104. 			richTextBoxClipboardContent.Visible = ( viewerwindow == ViewerType.RichText );
  105. 			textBoxClipboardContent.Visible = ( viewerwindow == ViewerType.Text );
  106. 			webView2ClipboardContent.Visible = ( viewerwindow == ViewerType.Web );
  107. 			labelFilename.Visible = ( viewerwindow != ViewerType.Text );
  108. 			switch ( viewerwindow )
  109. 			{
  110. 				case ViewerType.Picture:
  111. 					richTextBoxClipboardContent.Text = null;
  112. 					textBoxClipboardContent.Text = null;
  113. 					webView2ClipboardContent.SendToBack( );
  114. 					pictureBoxClipboardContent.BringToFront( );
  115. 					break;
  116. 				case ViewerType.RichText:
  117. 					pictureBoxClipboardContent.Image = null;
  118. 					textBoxClipboardContent.Text = null;
  119. 					webView2ClipboardContent.SendToBack( );
  120. 					richTextBoxClipboardContent.BringToFront( );
  121. 					break;
  122. 				case ViewerType.Text:
  123. 					pictureBoxClipboardContent.Image = null;
  124. 					richTextBoxClipboardContent.Text = null;
  125. 					webView2ClipboardContent.SendToBack( );
  126. 					textBoxClipboardContent.BringToFront( );
  127. 					break;
  128. 				case ViewerType.Web:
  129. 					pictureBoxClipboardContent.Image = null;
  130. 					richTextBoxClipboardContent.Text = null;
  131. 					textBoxClipboardContent.Text = null;
  132. 					webView2ClipboardContent.BringToFront( );
  133. 					break;
  134. 			}
  135. 		}
  136.  
  137.  
  138. 		private void CheckClipboard( )
  139. 		{
  140. 			labelFilename.Text = null;
  141. 			if ( Clipboard.ContainsText( ) )
  142. 			{
  143. 				ChangeViewerType( ViewerType.Text );
  144. 				clipboardtext = Clipboard.GetText( TextDataFormat.UnicodeText );
  145. 				textBoxClipboardContent.BackColor = Color.White;
  146. 				textBoxClipboardContent.ForeColor = Color.Black;
  147. 				textBoxClipboardContent.Text = clipboardtext;
  148. 			}
  149. 			else if ( Clipboard.ContainsImage( ) )
  150. 			{
  151. 				ChangeViewerType( ViewerType.Picture );
  152. 				pictureBoxClipboardContent.Image = Clipboard.GetImage( );
  153. 			}
  154. 			else if ( Clipboard.GetFileDropList( ) != null )
  155. 			{
  156. 				bool success = false;
  157. 				if ( Clipboard.GetFileDropList( ).Count == 1 )
  158. 				{
  159. 					success = Preview( Clipboard.GetFileDropList( )[0] );
  160. 				}
  161. 				if ( !success )
  162. 				{
  163. 					ChangeViewerType( ViewerType.Text );
  164. 					textBoxClipboardContent.Text = null;
  165. 					textBoxClipboardContent.BringToFront( );
  166. 					labelFilename.Text = null;
  167. 					labelFilename.Visible = false;
  168. 					List<string> files = new List<string>( );
  169. 					List<string> folders = new List<string>( );
  170. 					foreach ( var file in Clipboard.GetFileDropList( ) )
  171. 					{
  172. 						if ( Directory.Exists( file ) )
  173. 						{
  174. 							folders.Add( file );
  175. 						}
  176. 						else
  177. 						{
  178. 							files.Add( file );
  179. 						}
  180. 					}
  181. 					if ( folders.Count > 0 )
  182. 					{
  183. 						folders.Sort( );
  184. 						textBoxClipboardContent.Text = "Folders:" + Environment.NewLine + string.Join( Environment.NewLine, folders ) + Environment.NewLine + Environment.NewLine;
  185. 					}
  186. 					if ( files.Count > 0 )
  187. 					{
  188. 						files.Sort( );
  189. 						textBoxClipboardContent.Text += "Files:" + Environment.NewLine + string.Join( Environment.NewLine, files );
  190. 					}
  191. 				}
  192. 			}
  193. 			else
  194. 			{
  195. 				ChangeViewerType( ViewerType.Picture );
  196. 				textBoxClipboardContent.BackColor = Form.DefaultBackColor;
  197. 				textBoxClipboardContent.ForeColor = Color.Gray;
  198. 				textBoxClipboardContent.Text = string.Join( Environment.NewLine, Clipboard.GetDataObject( ).GetFormats( ).ToArray<string>( ) ); // requires Linq
  199. 			}
  200. 			textBoxClipboardContent.SelectionStart = 0;
  201. 			textBoxClipboardContent.SelectionLength = 0;
  202. 		}
  203.  
  204.  
  205. 		static bool CheckIfGhostScriptIsInstalled( )
  206. 		{
  207. 			string gspath;
  208. 			if ( Win3264( ) == 64 )
  209. 			{
  210. 				gspath = SearchPath( "gswin64c.exe" );
  211. 				if ( !string.IsNullOrWhiteSpace( gspath ) )
  212. 				{
  213. 					gsexec = gspath;
  214. 					return true;
  215. 				}
  216. 			}
  217. 			gspath = SearchPath( "gswin32c.exe" );
  218. 			if ( !string.IsNullOrWhiteSpace( gspath ) )
  219. 			{
  220. 				gsexec = gspath;
  221. 				return true;
  222. 			}
  223. 			RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" );
  224. 			var programs = uninstallKey.GetSubKeyNames( );
  225. 			foreach ( var program in programs )
  226. 			{
  227. 				if ( program.ToLower( ).Contains( "ghostscript" ) )
  228. 				{
  229. 					RegistryKey subkey = uninstallKey.OpenSubKey( program );
  230. 					string uninstallstring = subkey.GetValue( "UninstallString" ).ToString( );
  231. 					subkey.Close( );
  232. 					if ( !string.IsNullOrWhiteSpace( uninstallstring ) )
  233. 					{
  234. 						if ( File.Exists( Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin64.exe" ) )
  235. 						{
  236. 							gsexec = Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin64.exe";
  237. 						}
  238. 						else if ( File.Exists( Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin32.exe" ) )
  239. 						{
  240. 							gsexec = Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin32.exe";
  241. 						}
  242. 						break;
  243. 					}
  244. 				}
  245. 			}
  246. 			uninstallKey.Close( );
  247. 			if ( !string.IsNullOrWhiteSpace( gsexec ) )
  248. 			{
  249. 				return true;
  250. 			}
  251. 			if ( Win3264( ) == 64 )
  252. 			{
  253. 				uninstallKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" );
  254. 				programs = uninstallKey.GetSubKeyNames( );
  255. 				foreach ( var program in programs )
  256. 				{
  257. 					if ( program.ToLower( ).Contains( "ghostscript" ) )
  258. 					{
  259. 						RegistryKey subkey = uninstallKey.OpenSubKey( program );
  260. 						string uninstallstring = subkey.GetValue( "UninstallString" ).ToString( );
  261. 						subkey.Close( );
  262. 						if ( !string.IsNullOrWhiteSpace( uninstallstring ) )
  263. 						{
  264. 							if ( File.Exists( Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin32.exe" ) )
  265. 							{
  266. 								gsexec = Path.GetDirectoryName( uninstallstring ) + @"\bin\gswin32.exe";
  267. 							}
  268. 							break;
  269. 						}
  270. 					}
  271. 				}
  272. 				uninstallKey.Close( );
  273. 			}
  274. 			return string.IsNullOrWhiteSpace( gsexec );
  275. 		}
  276.  
  277.  
  278. 		private void CompactWindow( )
  279. 		{
  280. 			this.ClientSize = new Size( (int)( Screen.PrimaryScreen.Bounds.Width / 2 ), 40 );
  281. 			this.Location = new System.Drawing.Point( (int)( Screen.PrimaryScreen.Bounds.Width / 4 ), Screen.PrimaryScreen.Bounds.Height - 40 );
  282. 			this.TopLevel = true;
  283. 			this.ControlBox = false;
  284. 			this.Text = string.Empty;
  285. 			this.FormBorderStyle = FormBorderStyle.None;
  286. 			textBoxClipboardContent.Size = new Size( this.ClientSize.Width - 40, this.ClientSize.Height );
  287. 			textBoxClipboardContent.Location = new System.Drawing.Point( 0, 0 );
  288. 			textBoxClipboardContent.Font = new System.Drawing.Font( textBoxClipboardContent.Font.FontFamily, (float)( textBoxClipboardContent.Font.Size * fontsizefactor ), FontStyle.Regular );
  289. 			Button exitbutton = new Button
  290. 			{
  291. 				Text = "Exit",
  292. 				Size = new Size( 32, 32 ),
  293. 				Location = new System.Drawing.Point( this.ClientSize.Width - 36, 4 )
  294. 			};
  295. 			exitbutton.Click += Exitbutton_Click;
  296. 			this.Controls.Add( exitbutton );
  297. 		}
  298.  
  299.  
  300. 		private void DebugInfo( )
  301. 		{
  302. 			string programpath = System.Windows.Forms.Application.ExecutablePath;
  303. 			string[] arguments = Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  304. 			string installednetframework = GetInstalledNETFrameworkVersion( );
  305. 			string requirednetframework = GetRequiredNETFrameworkVersion( );
  306. 			string debuginfo = string.Format( "DEBUGGING INFO:{0}==============={0}Program path           : {1}{0}Required .NET version  : {2}{0}Installed .NET version : {3}{0}Command line arguments : {4}{0}Timer interval         : {5}{0}Modal window           : {6}", System.Environment.NewLine, programpath, requirednetframework, installednetframework, string.Join( " ", arguments ), interval, modalwindow );
  307. 			Clipboard.SetText( debuginfo );
  308. 		}
  309.  
  310.  
  311. 		private string Excel2PDF( string excelfile )
  312. 		{
  313. 			if ( !isExcelInstalled )
  314. 			{
  315. 				return null;
  316. 			}
  317. 			string pdffile = Path.GetTempFileName( ) + ".pdf";
  318. 			if ( pdffile != null )
  319. 			{
  320. 				tempfiles.Add( pdffile );
  321. 				Excel.Application excelapp = null;
  322. 				Excel.Workbook workbook = null;
  323. 				try
  324. 				{
  325. 					excelapp = new Excel.Application
  326. 					{
  327. 						Visible = false
  328. 					};
  329. 					object updatelinks = true;
  330. 					object openreadonly = true;
  331. 					workbook = excelapp.Workbooks.Open( excelfile, updatelinks, openreadonly );
  332. 					Excel.Worksheet sheet = (Excel.Worksheet)workbook.Worksheets[1];
  333. 					sheet.ExportAsFixedFormat( Excel.XlFixedFormatType.xlTypePDF, pdffile );
  334. 				}
  335. 				catch ( Exception ex )
  336. 				{
  337. 					MessageBox.Show( ex.Message + "\n\n" + ex.StackTrace );
  338. 				}
  339. 				finally
  340. 				{
  341. 					workbook?.Close( );
  342. 					excelapp?.Quit( );
  343. 				}
  344. 			}
  345. 			return pdffile;
  346. 		}
  347.  
  348.  
  349. 		private string GetInstalledNETFrameworkVersion( )
  350. 		{
  351. 			string rc = string.Empty;
  352. 			System.Collections.Generic.List<string> installedversions = new System.Collections.Generic.List<string>( );
  353. 			// Get the list of installed .NET Framework versions from the registry, by Microsoft:
  354. 			// https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
  355. 			using ( RegistryKey ndpKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, "" ).OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  356. 			{
  357. 				foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
  358. 				{
  359. 					if ( versionKeyName.StartsWith( "v" ) )
  360. 					{
  361. 						RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
  362. 						string name = (string) versionKey.GetValue( "Version", "" );
  363. 						if ( name == "" )
  364. 						{
  365. 							foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
  366. 							{
  367. 								RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
  368. 								name = (string) subKey.GetValue( "Version", "" );
  369. 								if ( name != "" )
  370. 								{
  371. 									installedversions.Add( name );
  372. 								}
  373. 							}
  374. 						}
  375. 						else
  376. 						{
  377. 							installedversions.Add( name );
  378. 						}
  379. 					}
  380. 				}
  381. 			}
  382. 			// Determine the highest version
  383. 			foreach ( string version in installedversions )
  384. 			{
  385. 				highestversion = HighestVersion( highestversion, version );
  386. 			}
  387. 			return string.Join( ".", highestversion.Select( x => x.ToString( ) ).ToArray( ) ); // requires System.Linq
  388. 		}
  389.  
  390.  
  391. 		static string GetRequiredNETFrameworkVersion( )
  392. 		{
  393. 			// Get the required .NET Framework version
  394. 			// By Fernando Gonzalez Sanchez on StackOverflow.com
  395. 			// https://stackoverflow.com/a/18623516
  396. 			object[] list = Assembly.GetExecutingAssembly( ).GetCustomAttributes( true );
  397. 			var attribute = list.OfType<TargetFrameworkAttribute>( ).First( ); // requires Linq
  398. 			//string frameworkname = attribute.FrameworkName;
  399. 			string frameworkdisplayname = attribute.FrameworkDisplayName;
  400. 			return frameworkdisplayname;
  401. 		}
  402.  
  403.  
  404. 		static int[] HighestVersion( int[] version1, string version2 )
  405. 		{
  406. 			int[] converted2 = version2.Split( ".".ToCharArray( ) ).Select( x => System.Convert.ToInt32( x ) ).ToArray( );
  407. 			int minlength = Math.Min( version1.Length, converted2.Length );
  408. 			for ( int i = 0; i < minlength; i++ )
  409. 			{
  410. 				if ( version1[i] > converted2[i] )
  411. 				{
  412. 					return version1;
  413. 				}
  414. 				else if ( version1[i] < converted2[i] )
  415. 				{
  416. 					return converted2;
  417. 				}
  418. 			}
  419. 			return version1;
  420. 		}
  421.  
  422.  
  423. 		private void ParseCommandLine( )
  424. 		{
  425. 			isRedirected = ( Console.IsOutputRedirected || Console.IsErrorRedirected );
  426. 			string[] arguments = Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  427. 			foreach ( string argument in arguments )
  428. 			{
  429. 				string clswitch = argument.Split( ":=".ToCharArray( ) )[0].ToUpper( );
  430. 				string clval = ( argument.IndexOfAny( ":=".ToCharArray( ) ) > 0 ? argument.Split( ":=".ToCharArray( ) )[1] : string.Empty );
  431. 				switch ( clswitch )
  432. 				{
  433. 					case "/CM":
  434. 						compactmode = true;
  435. 						break;
  436. 					case "/D":
  437. 					case "/DEBUG":
  438. 						debugmode = true;
  439. 						break;
  440. 					case "/F":
  441. 						int fontsizepercentage = 100;
  442. 						if ( !int.TryParse( clval, out fontsizepercentage ) )
  443. 						{
  444. 							errormessage = string.Format( "Invalid font size percentage: {0}", argument );
  445. 							ShowHelp( );
  446. 						}
  447. 						else if ( fontsizepercentage < 50 || fontsizepercentage > 150 )
  448. 						{
  449. 							errormessage = string.Format( "Font size percentage out of range (50..150): {0}", argument );
  450. 							ShowHelp( );
  451. 						}
  452. 						else
  453. 						{
  454. 							fontsizefactor = fontsizepercentage / 100F;
  455. 						}
  456. 						break;
  457. 					case "/NM":
  458. 						modalwindow = false;
  459. 						break;
  460. 					case "/?":
  461. 						ShowHelp( );
  462. 						break;
  463. 					default:
  464. 						errormessage = string.Format( "Invalid argument: {0}", argument );
  465. 						ShowHelp( );
  466. 						break;
  467. 				}
  468. 			}
  469. 		}
  470.  
  471.  
  472. 		private string PPT2JPG( string pptfile )
  473. 		{
  474. 			if ( !isPowerPointInstalled )
  475. 			{
  476. 				return null;
  477. 			}
  478. 			string jpgfile = Path.GetTempFileName( ) + ".jpg";
  479. 			tempfiles.Add( jpgfile );
  480. 			PowerPoint.Application pptapp = new PowerPoint.Application( );
  481. 			try
  482. 			{
  483. 				PowerPoint.Slide slide = pptapp.Presentations.Open( pptfile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse ).Slides[1];
  484. 				slide.Export( jpgfile, "JPG" );
  485. 			}
  486. 			catch
  487. 			{
  488. 				jpgfile = null;
  489. 			}
  490. 			finally
  491. 			{
  492. 				pptapp.Quit( );
  493. 			}
  494. 			return jpgfile;
  495. 		}
  496.  
  497.  
  498. 		private bool Preview( string filename )
  499. 		{
  500. 			labelFilename.Location = new System.Drawing.Point( 12, 325 );
  501. 			labelFilename.Width = textBoxClipboardContent.Width;
  502. 			labelFilename.Height = 30;
  503. 			labelFilename.TextAlign = ContentAlignment.MiddleCenter;
  504. 			labelFilename.BackColor = Color.Transparent;
  505. 			labelFilename.Visible = false;
  506. 			string tempfile;
  507. 			bool result = true;
  508. 			switch ( Path.GetExtension( filename ).ToLower( ) )
  509. 			{
  510. 				case ".ini":
  511. 				case ".log":
  512. 				case ".txt":
  513. 					ChangeViewerType( ViewerType.Text );
  514. 					textBoxClipboardContent.Text = File.ReadAllText( filename );
  515. 					ShowLabel( filename );
  516. 					break;
  517. 				case ".htm":
  518. 				case ".html":
  519. 				case ".pdf":
  520. 				case ".php":
  521. 				case ".xhtml":
  522. 					ChangeViewerType( ViewerType.Web );
  523. 					webView2ClipboardContent.Source = new Uri( filename );
  524. 					ShowLabel( filename );
  525. 					break;
  526. 				case ".bmp":
  527. 				case ".gif":
  528. 				case ".jpg":
  529. 				case ".jpeg":
  530. 				case ".png":
  531. 				case ".tif":
  532. 				case ".tiff":
  533. 					ChangeViewerType( ViewerType.Picture );
  534. 					pictureBoxClipboardContent.Image = Image.FromFile( filename );
  535. 					ShowLabel( filename );
  536. 					break;
  537. 				case ".mp3":
  538. 				case ".mp4":
  539. 				case ".webp":
  540. 					ChangeViewerType( ViewerType.Web );
  541. 					webView2ClipboardContent.Source = new Uri( filename );
  542. 					ShowLabel( filename );
  543. 					break;
  544. 				case ".epub":
  545. 					string tempdir = Path.Combine( Environment.GetEnvironmentVariable( "Temp" ), Path.GetFileNameWithoutExtension( filename ) );
  546. 					if ( Directory.Exists( tempdir ) )
  547. 					{
  548. 						Directory.Delete( tempdir, true );
  549. 					}
  550. 					else
  551. 					{
  552. 						Directory.CreateDirectory( tempdir );
  553. 					}
  554. 					tempdirs.Add( tempdir );
  555. 					System.IO.Compression.ZipFile.ExtractToDirectory( filename, tempdir );
  556. 					string cover = Directory.GetFiles( tempdir, "cover.jpg", SearchOption.AllDirectories ).FirstOrDefault( );
  557. 					if ( !File.Exists( cover ) )
  558. 					{
  559. 						cover = Directory.GetFiles( tempdir, "cover.jpeg", SearchOption.AllDirectories ).FirstOrDefault( );
  560. 					}
  561. 					if ( File.Exists( cover ) )
  562. 					{
  563. 						tempfiles.Add( cover );
  564. 						ChangeViewerType( ViewerType.Picture );
  565. 						pictureBoxClipboardContent.Image = Image.FromFile( cover );
  566. 						ShowLabel( filename );
  567. 					}
  568. 					else
  569. 					{
  570. 						ChangeViewerType( ViewerType.Text );
  571. 						textBoxClipboardContent.Text = "File:" + Environment.NewLine + filename;
  572. 					}
  573. 					break;
  574. 				case ".xls":
  575. 				case ".xlsx":
  576. 				case ".ods":
  577. 					tempfile = Excel2PDF( filename );
  578. 					if ( tempfile == null )
  579. 					{
  580. 						ChangeViewerType( ViewerType.Text );
  581. 						textBoxClipboardContent.Text = "File:" + Environment.NewLine + filename;
  582. 					}
  583. 					else
  584. 					{
  585. 						tempfiles.Add( tempfile );
  586. 						ChangeViewerType( ViewerType.Web );
  587. 						webView2ClipboardContent.Source = new Uri( tempfile );
  588. 						ShowLabel( filename );
  589. 					}
  590. 					break;
  591. 				case ".doc":
  592. 				case ".docx":
  593. 				case ".odt":
  594. 					tempfile = Word2RTF( filename );
  595. 					if ( tempfile == null )
  596. 					{
  597. 						ChangeViewerType( ViewerType.Text );
  598. 						textBoxClipboardContent.Text = "File:" + Environment.NewLine + filename;
  599. 					}
  600. 					else
  601. 					{
  602. 						tempfiles.Add( tempfile );
  603. 						ChangeViewerType( ViewerType.RichText );
  604. 						richTextBoxClipboardContent.Rtf = File.ReadAllText( tempfile, Encoding.UTF8 );
  605. 						ShowLabel( filename );
  606. 					}
  607. 					break;
  608. 				case ".pps":
  609. 				case ".ppsx":
  610. 				case ".ppt":
  611. 				case ".pptx":
  612. 				case ".odp":
  613. 					tempfile=PPT2JPG( filename );
  614. 					if ( tempfile == null )
  615. 					{
  616. 						ChangeViewerType( ViewerType.Text );
  617. 						textBoxClipboardContent.Text = "File:" + Environment.NewLine + filename;
  618. 					}
  619. 					else
  620.                     {
  621. 						ChangeViewerType( ViewerType.Picture );
  622. 						pictureBoxClipboardContent.Image = Image.FromFile( tempfile );
  623. 						ShowLabel( filename );
  624. 					}
  625. 					break;
  626. 				case ".rtf":
  627. 					ChangeViewerType( ViewerType.RichText );
  628. 					richTextBoxClipboardContent.Rtf = File.ReadAllText( filename, Encoding.UTF8 );
  629. 					ShowLabel( filename );
  630. 					break;
  631. 				default:
  632. 					ChangeViewerType( ViewerType.Text );
  633. 					result = false;
  634. 					break;
  635. 			}
  636. 			return result;
  637. 		}
  638.  
  639.  
  640. 		static string SearchPath( string execname )
  641. 		{
  642. 			foreach(string folder in Environment.GetEnvironmentVariable("PATH").Split( ';' ) )
  643. 			{
  644. 				if ( File.Exists( Path.Combine( folder, execname ) ) )
  645. 				{
  646. 					return Path.Combine( folder, execname );
  647. 				}
  648. 			}
  649. 			return null;
  650. 		}
  651.  
  652.  
  653. 		private void ShowHelp( )
  654. 		{
  655. 			string message = string.Empty;
  656. 			if ( !string.IsNullOrWhiteSpace( errormessage ) )
  657. 			{
  658. 				message += errormessage + "\n\n";
  659. 			}
  660. 			message += title;
  661. 			message += "\nMonitor clipboard content in realtime\n\n";
  662. 			message += "Usage:    MONITORCLIPBOARD.EXE  [ options ]\n\n";
  663. 			message += "Options:  /CM      Compact Mode: small window over taskbar\n";
  664. 			message += "                   (default: normal window at center of screen)\n";
  665. 			message += "          /F:perc  Font size percentage (50..150; default: 100)\n";
  666. 			message += "          /NM      sets the program's window to Non-Modal\n";
  667. 			message += "                   (default: always on top)\n";
  668. 			message += "          /D       Debug mode: send some debugging information\n";
  669. 			message += "                   to the clipboard (warning: this will overwrite\n";
  670. 			message += "                   the current clipboard content)\n\n";
  671. 			message += "Notes:    If the clipboard content is text or image, a preview will\n";
  672. 			message += "          be shown in the program window.\n";
  673. 			message += "          If the clipboard contains multiple files and/or folders,\n";
  674. 			message += "          the files and folders will be listed separately, sorted.\n";
  675. 			message += "          If the clipboard contains a single file, the program will\n";
  676. 			message += "          attempt to show a preview of the file's content, plus its path.\n";
  677. 			message += "          Supported file types are images, Microsoft Office and OpenOffice\n";
  678. 			message += "          text, spreadsheets and presentations, PDF and RTF.\n";
  679. 			message += "          These previews depend on software installed on the computer,\n";
  680. 			message += "          i.e. Microsoft Office and GhostScript.\n";
  681. 			message += "          if the required software is not found, the program will show\n";
  682. 			message += "          the file as a \"list of one file\".\n";
  683. 			message += "          Though invalid or duplicate arguments DO raise error\n";
  684. 			message += "          messages, they are ignored.\n\n";
  685. 			message += "Credits:  Clipboard changes notifications by Gert Lombard\n";
  686. 			message += "          https://gist.github.com/glombard/7986317\n";
  687. 			message += "          Console output from a WinForms program by Timm\n";
  688. 			message += "          https://www.csharp411.com/console-output-from-winforms-application/\n";
  689. 			message += "          Show text as RTF based on code by Wendy Zang\n";
  690. 			message += "          https://learn.microsoft.com/en-us/archive/msdn-technet-forums\n";
  691. 			message += "          /6e56af9b-d7d3-49f3-9ec4-80edde3fe54b#a64345e9-cfcb-43be-ab18-c08fae02cb2a\n";
  692. 			message += "          Hide menus in WebView2 viewer by jpine\n";
  693. 			message += "          https://stackoverflow.com/a/74018241\n\n";
  694. 			message += "Written by Rob van der Woude\n";
  695. 			message += "https://www.robvanderwoude.com";
  696. 			Console.WriteLine( message );
  697. 			Clipboard.SetText( message.Replace( "\n", Environment.NewLine ) );
  698. 		}
  699.  
  700.  
  701. 		private void ShowLabel( string text )
  702. 		{
  703. 			labelFilename.Text = text;
  704. 			labelFilename.Visible = true;
  705. 			labelFilename.BringToFront( );
  706. 		}
  707.  
  708.  
  709. 		static int Win3264( )
  710. 		{
  711. 			ManagementObjectSearcher searcher = new ManagementObjectSearcher( @"root\CIMV2", "SELECT * FROM Win32_Processor" );
  712. 			foreach ( ManagementObject queryObj in searcher.Get( ).Cast<ManagementObject>( ) )
  713. 			{
  714. 				return (int)(UInt16)( queryObj["AddressWidth"] );
  715. 			}
  716. 			return 0;
  717. 		}
  718.  
  719.  
  720. 		private string Word2RTF( string filename )
  721. 		{
  722. 			if(!isWordInstalled)
  723. 			{
  724. 				return null;
  725. 			}
  726. 			string rtffile = Path.GetTempFileName( ) + ".rtf";
  727. 			tempfiles.Add( rtffile );
  728. 			Word.Application wordapp = new Word.Application( );
  729. 			object savechanges = Word.WdSaveOptions.wdDoNotSaveChanges;
  730. 			try
  731. 			{
  732. 				wordapp.Visible = false;
  733. 				Word.Document worddoc = wordapp.Documents.Open( filename );
  734. 				worddoc.SaveAs2( rtffile, Word.WdSaveFormat.wdFormatRTF );
  735. 				worddoc.Close( savechanges );
  736. 			}
  737. 			finally
  738. 			{
  739. 				wordapp.Quit( savechanges );
  740. 			}
  741. 			return rtffile;
  742. 		}
  743.  
  744.  
  745. 		private void ClipboardNotification_ClipboardUpdate( object sender, EventArgs e )
  746. 		{
  747. 			CheckClipboard( );
  748. 		}
  749.  
  750.  
  751. 		private void Exitbutton_Click( object sender, EventArgs e )
  752. 		{
  753. 			System.Windows.Forms.Application.Exit( );
  754. 		}
  755.  
  756.  
  757. 		private void FormMonitorClipboard_FormClosing( object sender, FormClosingEventArgs e )
  758. 		{
  759. 			pictureBoxClipboardContent.Image = null;
  760. 			pictureBoxClipboardContent.Dispose( );
  761. 			richTextBoxClipboardContent.Text = null;
  762. 			richTextBoxClipboardContent.Dispose( );
  763. 			textBoxClipboardContent.Text = null;
  764. 			textBoxClipboardContent.Dispose( );
  765. 			webView2ClipboardContent.Dispose( );
  766. 			foreach ( string tempfile in tempfiles )
  767. 			{
  768. 				try
  769. 				{
  770. 					File.Delete( tempfile );
  771. 				}
  772. 				catch
  773. 				{
  774. 					// ignore
  775. 				}
  776. 			}
  777. 			foreach ( string tempdir in tempdirs )
  778. 			{
  779. 				try
  780. 				{
  781. 					Directory.Delete( tempdir, true );
  782. 				}
  783. 				catch
  784. 				{
  785. 					// ignore
  786. 				}
  787. 			}
  788. 		}
  789.  
  790.  
  791. 		private void FormMonitorClipboard_HelpRequested( object sender, HelpEventArgs hlpevent )
  792. 		{
  793. 			ShowHelp( );
  794. 		}
  795.  
  796.  
  797. 		[DllImport( "kernel32.dll" )]
  798. 		static extern bool AttachConsole( int dwProcessId );
  799. 		private const int ATTACH_PARENT_PROCESS = -1;
  800.  
  801.  
  802. 		#region Clipboard Changes Notification
  803.  
  804. 		// Code by Gert Lombard on https://gist.github.com/glombard/7986317
  805.  
  806. 		/// <summary>
  807. 		/// Provides notifications when the contents of the clipboard is updated.
  808. 		/// </summary>
  809. 		public sealed class ClipboardNotification
  810. 		{
  811. 			/// <summary>
  812. 			/// Occurs when the contents of the clipboard is updated.
  813. 			/// </summary>
  814. 			public static event EventHandler ClipboardUpdate;
  815.  
  816. 			private static NotificationForm _form = new NotificationForm( );
  817.  
  818. 			/// <summary>
  819. 			/// Raises the <see cref="ClipboardUpdate"/> event.
  820. 			/// </summary>
  821. 			/// <param name="e">Event arguments for the event.</param>
  822. 			private static void OnClipboardUpdate( EventArgs e )
  823. 			{
  824. 				var handler = ClipboardUpdate;
  825. 				if ( handler != null )
  826. 				{
  827. 					handler( null, e );
  828. 				}
  829. 			}
  830.  
  831.  
  832. 			/// <summary>
  833. 			/// Hidden form to recieve the WM_CLIPBOARDUPDATE message.
  834. 			/// </summary>
  835. 			private class NotificationForm : Form
  836. 			{
  837. 				public NotificationForm( )
  838. 				{
  839. 					NativeMethods.SetParent( Handle, NativeMethods.HWND_MESSAGE );
  840. 					NativeMethods.AddClipboardFormatListener( Handle );
  841. 				}
  842.  
  843. 				protected override void WndProc( ref Message m )
  844. 				{
  845. 					if ( m.Msg == NativeMethods.WM_CLIPBOARDUPDATE )
  846. 					{
  847. 						OnClipboardUpdate( null );
  848. 					}
  849. 					base.WndProc( ref m );
  850. 				}
  851. 			}
  852. 		}
  853.  
  854. 		internal static class NativeMethods
  855. 		{
  856. 			// See http://msdn.microsoft.com/en-us/library/ms649021%28v=vs.85%29.aspx
  857. 			public const int WM_CLIPBOARDUPDATE = 0x031D;
  858. 			public static IntPtr HWND_MESSAGE = new IntPtr( -3 );
  859. 			// See http://msdn.microsoft.com/en-us/library/ms632599%28VS.85%29.aspx#message_only
  860. 			[DllImport( "user32.dll", SetLastError = true )]
  861. 			[return: MarshalAs( UnmanagedType.Bool )]
  862. 			public static extern bool AddClipboardFormatListener( IntPtr hwnd );
  863. 			// See http://msdn.microsoft.com/en-us/library/ms633541%28v=vs.85%29.aspx
  864. 			// See http://msdn.microsoft.com/en-us/library/ms649033%28VS.85%29.aspx
  865. 			[DllImport( "user32.dll", SetLastError = true )]
  866. 			public static extern IntPtr SetParent( IntPtr hWndChild, IntPtr hWndNewParent );
  867. 		}
  868.  
  869. 		#endregion Clipboard Changes Notification
  870. 	}
  871.  
  872.  
  873. 	public enum ViewerType
  874. 	{
  875. 		Picture,
  876. 		RichText,
  877. 		Text,
  878. 		Web
  879. 	}
  880. }

page last modified: 2024-04-16; loaded in 0.0162 seconds