Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for audioendpoints.cs

(view source code of audioendpoints.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.Windows.Forms;
  7. using NAudio.CoreAudioApi;
  8.  
  9.  
  10. namespace AudioEndPoints
  11. {
  12. 	public partial class FormAudioEndPoints : Form
  13. 	{
  14. 		public FormAudioEndPoints( )
  15. 		{
  16. 			InitializeComponent( );
  17. 		}
  18.  
  19.  
  20. 		static readonly string progver = "1.02";
  21.  
  22.  
  23. 		static bool bgcolors = true;
  24. 		static bool fgcolors = false;
  25. 		static bool helprequested = false;
  26. 		static bool linear = true;
  27. 		static readonly Dictionary<DeviceState, Color> foregroundcolors = new Dictionary<DeviceState, Color>
  28. 		{
  29. 			[DeviceState.Active] = Color.Green,
  30. 			[DeviceState.Disabled] = Color.Orange,
  31. 			[DeviceState.NotPresent] = Color.SlateGray,
  32. 			[DeviceState.Unplugged] = Color.Red
  33. 		};
  34. 		static readonly Dictionary<DeviceState, Color> backgroundcolors = new Dictionary<DeviceState, Color>
  35. 		{
  36. 			[DeviceState.Active] = Color.LightGreen,
  37. 			[DeviceState.Disabled] = Color.Yellow,
  38. 			[DeviceState.NotPresent] = Color.LightGray,
  39. 			[DeviceState.Unplugged] = Color.Red
  40. 		};
  41.  
  42.  
  43. 		private void DataGridView1_KeyUp( object sender, KeyEventArgs e )
  44. 		{
  45. 			if ( e.KeyCode == Keys.F1 )
  46. 			{
  47. 				ShowHelp( false );
  48. 			}
  49. 			if ( e.KeyCode == Keys.Escape )
  50. 			{
  51. 				Application.Exit( );
  52. 			}
  53. 			if ( e.Control && e.KeyCode == Keys.P )
  54. 			{
  55. 				PrintDataGridView( );
  56. 			}
  57. 			if ( e.Control && e.KeyCode == Keys.S )
  58. 			{
  59. 				string filename = string.Format( "AudioEndPoints.{0}.{1}.txt", Environment.GetEnvironmentVariable( "COMPUTERNAME" ), DateTime.Now.ToString( "yyyy-MM-dd_HHmmss" ) );
  60. 				string outfile = Path.Combine( Environment.CurrentDirectory, filename );
  61. 				SaveDataGridView( outfile );
  62. 				MessageBox.Show( "Saved as \"" + filename + "\" in folder \"" + Path.GetDirectoryName( outfile ) + "\"", "File Saved", MessageBoxButtons.OK, MessageBoxIcon.Information );
  63. 			}
  64. 		}
  65.  
  66.  
  67. 		private void DataGridView1_SortCompare( object sender, DataGridViewSortCompareEventArgs e )
  68. 		{
  69. 			if ( e.Column.Index == 0 )
  70. 			{
  71. 				e.SortResult = int.Parse( e.CellValue1.ToString( ) ).CompareTo( int.Parse( e.CellValue2.ToString( ) ) );
  72. 				e.Handled = true; // skip the default sorting
  73. 			}
  74. 		}
  75.  
  76.  
  77. 		private void FormAudioEndPoints_FormClosed( object sender, FormClosedEventArgs e )
  78. 		{
  79. 			if ( helprequested )
  80. 			{
  81. 				ShowHelp( true );
  82. 				Environment.ExitCode = 0;
  83. 				Application.Exit( );
  84. 			}
  85. 		}
  86.  
  87.  
  88. 		private void FormAudioEndPonts_Load( object sender, EventArgs e )
  89. 		{
  90. 			this.Text = "AudioEndPoints.exe, \u00A0 Version " + progver + " \u00A0?\u00A0 \u00A0 Copyright \u00A9 2025 Rob van der Woude";
  91. 			string commandline = Environment.CommandLine.ToUpper( );
  92. 			if ( commandline.Contains( "?" ) )
  93. 			{
  94. 				ShowHelp( true );
  95. 				Environment.ExitCode = -1;
  96. 				Application.Exit( );
  97. 			}
  98.  
  99. 			if ( commandline.Contains( "/F" ) )
  100. 			{
  101. 				bgcolors = false;
  102. 				fgcolors = true;
  103. 			}
  104. 			else if ( commandline.Contains( "/BW" ) )
  105. 			{
  106. 				bgcolors = false;
  107. 				fgcolors = false;
  108. 			}
  109. 			linear = !commandline.Contains( "/DB" );
  110. 			SetupDataGridView( );
  111. 			PopulateDataGridView( );
  112. 		}
  113.  
  114.  
  115. 		private void PopulateDataGridView( )
  116. 		{
  117. 			MMDeviceEnumerator enumerator = new MMDeviceEnumerator( );
  118. 			int row = 0;
  119. 			foreach ( MMDevice endpoint in enumerator.EnumerateAudioEndPoints( DataFlow.All, DeviceState.All ) )
  120. 			{
  121. 				// Volume reading based on code by Mike de Klerk
  122. 				// https://stackoverflow.com/a/12534584
  123. 				string volume = string.Empty;
  124. 				if ( endpoint.State == DeviceState.Active )
  125. 				{
  126. 					if ( linear )
  127. 					{
  128. 						volume = string.Format( "{0} %", (int)( endpoint.AudioEndpointVolume.MasterVolumeLevelScalar * 100 ) );
  129. 					}
  130. 					else
  131. 					{
  132. 						volume = string.Format( "{0} dB", (int)endpoint.AudioEndpointVolume.MasterVolumeLevel );
  133. 					}
  134. 				}
  135. 				string[] line = { row.ToString( ), ( endpoint.DataFlow == DataFlow.Capture ? "IN" : "OUT" ), endpoint.FriendlyName, endpoint.State.ToString( ), endpoint.ID, volume };
  136. 				dataGridView1.Rows.Add( line );
  137. 				if ( bgcolors )
  138. 				{
  139. 					dataGridView1.Rows[row].DefaultCellStyle.BackColor = backgroundcolors[endpoint.State];
  140. 				}
  141. 				if ( fgcolors )
  142. 				{
  143. 					dataGridView1.Rows[row].DefaultCellStyle.ForeColor = foregroundcolors[endpoint.State];
  144. 				}
  145. 				row++;
  146. 			}
  147. 			dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  148. 			dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  149. 			dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  150. 			dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  151. 			dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
  152. 			dataGridView1.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
  153. 		}
  154.  
  155.  
  156. 		private void PrintDataGridView( )
  157. 		{
  158. 			string printout = Path.GetTempFileName( );
  159. 			SaveDataGridView( printout );
  160. 			ProcessStartInfo psi = new ProcessStartInfo
  161. 			{
  162. 				UseShellExecute = false,
  163. 				Arguments = string.Format( "/p \"{0}\"", printout ),
  164. 				FileName = "notepad.exe"
  165. 			};
  166. 			Process proc = Process.Start( psi );
  167. 			proc.WaitForExit( );
  168. 			File.Delete( printout );
  169. 		}
  170.  
  171.  
  172. 		private void SaveDataGridView( string outfile )
  173. 		{
  174. 			// line out colums
  175. 			int[] cw = new int[] { 5, 6, 0, 0, 0 };
  176. 			for ( int i = 0; i < dataGridView1.Columns.Count; i++ )
  177. 			{
  178. 				for ( int j = 0; j < dataGridView1.Rows.Count; j++ )
  179. 				{
  180. 					if ( dataGridView1.Rows[j].Cells[i].Value != null && dataGridView1.Rows[j].Cells[i].Value.ToString( ).Length > cw[i] )
  181. 					{
  182. 						cw[i] = dataGridView1.Rows[j].Cells[i].Value.ToString( ).Length;
  183. 					}
  184. 				}
  185. 			}
  186.  
  187. 			// format printout
  188. 			List<string> lines = new List<string>( );
  189. 			string linetemplate = "{0,-" + cw[0] + "}    {1,-" + cw[1] + "}    {2,-" + cw[2] + "}    {3,-" + cw[3] + "}    {4,-" + cw[4] + "}";
  190. 			// header
  191. 			var cols = dataGridView1.Columns;
  192. 			string headerline = string.Format( linetemplate, cols[0].HeaderText, cols[1].HeaderText.Replace( "\u00A0", "" ), cols[2].HeaderText, cols[3].HeaderText, cols[4].HeaderText );
  193. 			lines.Add( headerline );
  194. 			// rows
  195. 			for ( int i = 0; i < dataGridView1.Rows.Count; i++ )
  196. 			{
  197. 				var cells = dataGridView1.Rows[i].Cells;
  198. 				string line = string.Format( linetemplate, cells[0].Value, cells[1].Value, cells[2].Value, cells[3].Value, cells[4].Value );
  199. 				lines.Add( line );
  200. 			}
  201.  
  202. 			using ( StreamWriter print = new StreamWriter( outfile ) )
  203. 			{
  204. 				for ( int i = 0; i < lines.Count; i++ )
  205. 				{
  206. 					print.WriteLine( lines[i] );
  207. 				}
  208. 			}
  209. 		}
  210.  
  211.  
  212. 		private void SetupDataGridView( )
  213. 		{
  214. 			dataGridView1.ColumnCount = 6;
  215.  
  216. 			dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
  217. 			dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
  218. 			dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font( dataGridView1.Font, FontStyle.Bold );
  219.  
  220. 			dataGridView1.Location = new Point( 8, 8 );
  221. 			dataGridView1.Size = new Size( 500, 250 );
  222. 			dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
  223. 			dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
  224. 			dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.Single;
  225. 			dataGridView1.GridColor = Color.Black;
  226. 			dataGridView1.RowHeadersVisible = false;
  227.  
  228. 			dataGridView1.Columns[0].Name = "Index";
  229. 			dataGridView1.Columns[1].Name = "In\u00A0/\u00A0Out";
  230. 			dataGridView1.Columns[2].Name = "Name";
  231. 			dataGridView1.Columns[3].Name = "Status";
  232. 			dataGridView1.Columns[4].Name = "ID";
  233. 			dataGridView1.Columns[5].Name = "Volume";
  234. 			dataGridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
  235.  
  236. 			dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
  237. 			dataGridView1.MultiSelect = false;
  238. 			dataGridView1.Dock = DockStyle.Fill;
  239. 		}
  240.  
  241.  
  242. 		private void ShowHelp( bool cli = false )
  243. 		{
  244. 			string message = string.Format( "\nAudioEndPoints.exe,  Version {0}\n", progver );
  245. 			message += "List the local computer's audio endpoints\n\n";
  246. 			message += "Usage:\tAudioEndPoints.exe\t[ /F | /BW ]  [ /DB ]\n\n";
  247. 			message += "Where:\t                  \t/F \tuses status dependent\n";
  248. 			message += "      \t                  \t   \tFOREGROUND colors,\n";
  249. 			message += "      \t                  \t/BW\tuses BLACK and WHITE,\n";
  250. 			message += "      \t                  \t   \tdefault is status\n";
  251. 			message += "      \t                  \t   \tdependent BACKGROUND\n";
  252. 			message += "      \t                  \t/DB\tshows volume in dB,\n";
  253. 			message += "      \t                  \t   \tdefault is percentage\n\n";
  254. 			message += "Click on ANY column header to sort the table by that column.\n";
  255. 			message += "You can edit all cells, if you like.\n\n";
  256. 			message += "Keys:   \tCtrl+P will print the list,\n";
  257. 			message += "        \tCtrl+S will save it in a text file,\n";
  258. 			message += "        \tF1 will show this help text,\n";
  259. 			message += "        \tCtrl+C will copy the SELECTED LINE to the clipboard,\n";
  260. 			message += "        \tEscape will abort the program.\n\n";
  261. 			message += "Credits:\tTo access audio endpoints, this program uses\n";
  262. 			message += "        \tNAudio created by Mark Heath:\n";
  263. 			message += "        \thttps://github.com/naudio/NAudio\n";
  264. 			message += "        \tVolume reading based on code by Mike de Klerk:\n";
  265. 			message += "        \thttps://stackoverflow.com/a/12534584\n";
  266. 			message += "        \tOutput to parent console by Timm:\n";
  267. 			message += "        \twww.csharp411.com/console-output-from-winforms-application/\n\n";
  268. 			message += "Written by Rob van der Woude\n";
  269. 			message += "https://www.robvanderwoude.com\n";
  270.  
  271. 			if ( !cli )
  272. 			{
  273. 				helprequested = true;
  274. 				MessageBox.Show( message, "AudioEndPoints.exe, \u00A0 Version " + progver );
  275. 			}
  276. 			else
  277. 			{
  278. 				Console.WriteLine( message );
  279. 			}
  280. 		}
  281. 	}
  282. }

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