(view source code of dialogboxes_common.cs as plain text)
using System.Linq;
namespace RobvanderWoude
{
[System.Runtime.InteropServices.ClassInterface( System.Runtime.InteropServices.ClassInterfaceType.None )]
[System.Runtime.InteropServices.ComVisible( false )]
public class Global
{
[System.Runtime.InteropServices.ComVisible( false )]
public class Common
{
public static int[] BorderDimensions( )
{
System.Windows.Forms.Form testform = new System.Windows.Forms.Form( );
System.Drawing.Size testsize = new System.Drawing.Size( 300, 200 );
testform.Size = testsize;
int deltaX = testform.Size.Width - testform.ClientSize.Width + System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width - System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
int deltaY = testform.Size.Height - testform.ClientSize.Height + System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height - System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
testform.Dispose( );
return new int[] { deltaX, deltaY };
}
// Available standard console colors;
// do NOT change the order of these values,
// even if it seems illogical at index 7 and 8
public static int[] consolecolors = new int[] {
0x000000, // 0 Black
0x000080, // 1 DarkBlue
0x008000, // 2 DarkGreen
0x008080, // 3 DarkCyan
0x800000, // 4 DarkRed
0x800080, // 5 DarkMagenta
0x808000, // 6 DarkYellow
0xC0C0C0, // 7 Gray
0x808080, // 8 DarkGray
0x0000FF, // 9 Blue
0x00FF00, // A Green
0x00FFFF, // B Cyan
0xFF0000, // C Red
0xFF00FF, // D Magenta
0xFFFF00, // E Yellow
0xFFFFFF // F White
};
public static string Credits( )
{
string credits = "Credits";
credits += "\n" + new string( '\u2550', credits.Length ) + "\n\n";
credits += "Building COM Objects in C# by Mubbasher Adeel:\n";
credits += "https://www.codeproject.com/Articles/7859/Building-COM-Objects-in-C\n\n";
credits += "On-the-fly forms by Gorkem Gencay on StackOverflow.com:\n";
credits += "http://stackoverflow.com/questions/97097#17546909\n\n";
credits += "Localize captions by Martin Stoeckli:\n";
credits += "http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources\n\n";
credits += "Extract icons from Shell32.dll by Thomas Levesque on StackOverflow.com:\n";
credits += "http://stackoverflow.com/questions/6873026\n\n";
credits += "Get ISO week of year by \"il_guru\" on StackOverflow.com:\n";
credits += "https://stackoverflow.com/a/11155102\n\n";
credits += "Check if a font is a fixed pitch font, tip from Hans Passant on StackOverflow.com:\n";
credits += "https://stackoverflow.com/q/21965321\n\n";
credits += "Extension method to limit number to range by \"dtb\" on StackOverflow.com:\n";
credits += "https://stackoverflow.com/a/3176628\n\n";
credits += "Mask language table by Microsoft:\n";
credits += "http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx\n\n";
credits += "And last but not least, thanks for Wolfgang Struensee,\n";
credits += "for testing the many pre-release versions of this DLL\n\n";
return credits;
}
public static string GetCultureFromDateTimeString( string datetimestring )
{
System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>( );
foreach ( System.Globalization.CultureInfo cultureinfo in System.Globalization.CultureInfo.GetCultures( System.Globalization.CultureTypes.AllCultures ) )
{
try
{
System.DateTime test = System.DateTime.Parse( datetimestring, cultureinfo );
result.Add( string.Format( "{0} {1,-40} {2}", cultureinfo.Name, cultureinfo.DisplayName, System.DateTime.Now.ToString( cultureinfo ) ) );
}
catch { };
}
result.Sort( );
return result.Count.ToString( ) + "\n\n" + string.Join( "\n", result.ToArray( ) );
}
public static int GetIso8601WeekOfYear( System.DateTime date )
{
// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
// Code by "il_guru" on StackOverflow.com:
// https://stackoverflow.com/a/11155102
//
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll be the same
// week# as whatever Thursday, Friday or Saturday are, and we always get those right
System.DayOfWeek day = System.Globalization.CultureInfo.InvariantCulture.Calendar.GetDayOfWeek( date );
if ( day >= System.DayOfWeek.Monday && day <= System.DayOfWeek.Wednesday )
{
date = date.AddDays( 3 );
}
// Return the week of our adjusted day
return System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear( date, System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday );
}
public static System.Globalization.DateTimeFormatInfo GetDateTimeFormat( string culture ) => System.Globalization.CultureInfo.GetCultureInfo( culture ).DateTimeFormat;
public static bool TestIfRegexPattern( string pattern )
{
if ( string.IsNullOrWhiteSpace( pattern ) )
{
return false;
}
try
{
return System.Text.RegularExpressions.Regex.IsMatch( "", pattern );
}
catch ( System.ArgumentException )
{
return false;
}
}
public static string TimeStamp( )
{
return System.DateTime.Now.ToString( "[yyyy-MM-dd HH:mm:ss.fff] " );
}
[System.Runtime.InteropServices.ComVisible( false )]
public class Help
{
public static string _checkupdate = "Check the developer's website for updates";
public static string _credits = "Shows credits";
public static string _help = "Returns this help text as plain text, or if optional parameter equals 1, as html";
public static string _listproperties = "Returns a list of this class' properties as key=value pairs (1 per line)";
public static string _samplecode = "Returns VBScript sample code for this dialog";
public static string captioncancel = "Caption for \"Cancel\" button";
public static string captionok = "Caption for \"OK\" button";
public static string debuginfo = "A log of actions for debugging";
public static string errors = "List of errors with current settings";
public static string fixedpitchonly = "Allow only monospaced fonts (0=false; 1=true)";
public static string fontfamily = "Font family used in dialog";
public static string fontsize = "Font size used in dialog";
public static string left = "Offset of window from left screen border";
public static string literal = "Treat \"prompt\" as literal string (0=false; 1=true)";
public static string localizecaptions = "Use localized button captions (0=false; 1=true)";
public static string modal = "Modal dialog, i.e. always on top (0=false; 1=true)";
public static string prompt = "Optional text above controls";
public static string timeout = "Optional dialog timeout in seconds (0=no timeout)";
public static string timeoutelapsed = "Timeout elapsed status (0=false; 1=true)";
public static string title = "Dialog window title";
public static string top = "Offset of window from top of screen";
public static string version = "Show this DLL's version";
public static string windowheight = "Height of dialog window";
public static string windowwidth = "Width of dialog window";
public static System.Collections.Generic.List<string> HelpTableCell( string celltext, int textwidth )
{
System.Collections.Generic.List<string> colcells = new System.Collections.Generic.List<string>( );
string[] textlines = celltext.Split( "\n".ToCharArray( ) );
foreach ( string line in textlines )
{
string textline = line;
while ( textline.Length > 0 )
{
if ( textline.Length <= textwidth )
{
colcells.Add( textline );
textline = string.Empty;
}
else
{
int lastspace = textline.Substring( 0, textwidth ).LastIndexOf( ' ' );
int lastsemicolon = textline.Substring( 0, textwidth ).LastIndexOf( ';' );
int lastcomma = textline.Substring( 0, textwidth ).LastIndexOf( ',' );
int lasthyphen = textline.Substring( 0, textwidth ).LastIndexOf( '-' );
if ( lastspace > -1 )
{
colcells.Add( textline.Substring( 0, lastspace ).Trim( " \t\n\r".ToCharArray( ) ) );
textline = textline.Substring( lastspace ).Trim( " \t\n\r".ToCharArray( ) );
}
else if ( lastsemicolon > -1 )
{
colcells.Add( textline.Substring( 0, lastsemicolon ).Trim( " \t\n\r".ToCharArray( ) ) );
textline = textline.Substring( lastsemicolon ).Trim( " \t\n\r".ToCharArray( ) );
}
else if ( lastcomma > -1 )
{
colcells.Add( textline.Substring( 0, lastcomma ).Trim( " \t\n\r".ToCharArray( ) ) );
textline = textline.Substring( lastcomma ).Trim( " \t\n\r".ToCharArray( ) );
}
else if ( lasthyphen > -1 )
{
colcells.Add( textline.Substring( 0, lasthyphen ).Trim( " \t\n\r".ToCharArray( ) ) );
textline = textline.Substring( lasthyphen ).Trim( " \t\n\r".ToCharArray( ) );
}
else
{
colcells.Add( textline.Substring( 0, textwidth ).Trim( " \t\n\r".ToCharArray( ) ) );
textline = textline.Substring( textwidth ).Trim( " \t\n\r".ToCharArray( ) );
}
}
}
}
return colcells;
}
public static string HelpTableRowHTML( string col1text, string col2text, string col3text )
{
string row = "<tr>\n";
row += string.Format( "\t<td>{0}</td>\n", col1text );
row += string.Format( "\t<td>{0}</td>\n", col2text );
row += string.Format( "\t<td>{0}</td>\n", col3text );
row += "</tr>\n";
return row;
}
public static string HelpTableRowHTML( string col1text, string col2text, string col3text, string col4text, string col5text )
{
string row = "<tr>\n";
row += string.Format( "\t<td>{0}</td>\n", col1text );
row += string.Format( "\t<td>{0}</td>\n", col2text );
row += string.Format( "\t<td>{0}</td>\n", col3text );
row += string.Format( "\t<td>{0}</td>\n", col4text );
row += string.Format( "\t<td>{0}</td>\n", col5text );
row += "</tr>\n";
return row;
}
public static string HelpTableRowText( string template, string col1text, string col2text, string col3text, string col4text, string col5text )
{
string row = string.Empty;
int rows = 0;
int columns = 5;
int[] colwidth = { 0, 0, 0, 0, 0 };
string[] coltext = { col1text, col2text, col3text, col4text, col5text };
// Parse the linetemplate string to get the columns' widths
string pattern = @"\{(\d+),-?(\d+)\}";
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex( pattern );
System.Text.RegularExpressions.MatchCollection matches = regex.Matches( template );
//string text = string.Empty;
foreach ( System.Text.RegularExpressions.Match match in matches )
{
System.Text.RegularExpressions.GroupCollection groups = match.Groups;
colwidth[int.Parse( groups[1].Value )] = int.Parse( groups[2].Value );
}
for ( int i = 0; i < columns; i++ )
{
if ( colwidth[i] == 0 )
{
columns = i;
break;
}
}
// Wrap strings containing newlines and/or lines that are too long for their column
System.Collections.Generic.List<string> col1cells = new System.Collections.Generic.List<string>( );
if ( columns >= 1 )
{
col1cells = HelpTableCell( coltext[0], colwidth[0] );
rows = System.Math.Max( rows, col1cells.Count );
}
System.Collections.Generic.List<string> col2cells = new System.Collections.Generic.List<string>( );
if ( columns >= 2 )
{
col2cells = HelpTableCell( coltext[1], colwidth[1] );
rows = System.Math.Max( rows, col2cells.Count );
}
System.Collections.Generic.List<string> col3cells = new System.Collections.Generic.List<string>( );
if ( columns >= 3 )
{
col3cells = HelpTableCell( coltext[2], colwidth[2] );
rows = System.Math.Max( rows, col3cells.Count );
}
System.Collections.Generic.List<string> col4cells = new System.Collections.Generic.List<string>( );
if ( columns >= 4 )
{
col4cells = HelpTableCell( coltext[3], colwidth[3] );
rows = System.Math.Max( rows, col4cells.Count );
}
System.Collections.Generic.List<string> col5cells = new System.Collections.Generic.List<string>( );
if ( columns >= 5 )
{
col5cells = HelpTableCell( coltext[4], colwidth[4] );
rows = System.Math.Max( rows, col5cells.Count );
}
for ( int i = 0; i < rows; i++ )
{
col1cells.Add( "" );
col2cells.Add( "" );
col3cells.Add( "" );
col4cells.Add( "" );
col5cells.Add( "" );
row += string.Format( template, col1cells[i], col2cells[i], col3cells[i], col4cells[i], col5cells[i] );
}
return row;
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public class Lists
{
public static System.Collections.Generic.List<string> ConsoleColors( )
{
System.Collections.Generic.List<string> consolecolors = new System.Collections.Generic.List<string>( );
foreach ( int color in typeof( ConsoleColors ).GetEnumValues( ) )
{
string name = typeof( ConsoleColors ).GetEnumName( color );
consolecolors.Add( name + "=0X" + color.ToString( "X6" ) );
}
consolecolors.Sort( );
return consolecolors;
}
public static System.Collections.Generic.List<string> Cultures( )
{
return System.Globalization.CultureInfo.GetCultures( System.Globalization.CultureTypes.AllCultures ).Select( c => c.Name ).ToList<string>( );
}
public static System.Collections.Generic.List<string> KnownColors( )
{
System.Collections.Generic.List<string> allcolors = new System.Collections.Generic.List<string>( );
System.Drawing.KnownColor[] colors = (System.Drawing.KnownColor[]) System.Enum.GetValues( typeof( System.Drawing.KnownColor ) );
foreach ( System.Drawing.KnownColor knowncolor in colors )
{
System.Drawing.Color color = System.Drawing.Color.FromKnownColor( knowncolor );
allcolors.Add( string.Format( "{0}=0x{1:X6}", color.Name, (uint) color.ToArgb( ) % 0x01000000 ) );
}
allcolors.Sort( );
return allcolors;
}
public static string MaskLanguageTable( )
{
string text = string.Empty;
string separatorline = "\u251C" + new string( '\u2500', 12 ) + "\u253C" + new string( '\u2500', 82 ) + "\u2524\n";
string linetemplate = "\u2502 {0,-10} \u2502 {1,-80} \u2502\n";
text = "System.Windows.Forms.MaskedTextBox.Mask Property";
text += "\n" + new string( '\u2550', text.Length ) + "\n\n";
text += "\u250C" + new string( '\u2500', 12 ) + "\u252C" + new string( '\u2500', 82 ) + "\u2510\n";
text += string.Format( linetemplate, "Masking", string.Empty );
text += string.Format( linetemplate, "element", "Description" );
text += "\u255E" + new string( '\u2550', 12 ) + "\u256A" + new string( '\u2550', 82 ) + "\u2561\n";
text += string.Format( linetemplate, "0", "Digit, required. This element will accept any single digit between 0 and 9." );
text += separatorline;
text += string.Format( linetemplate, "9", "Digit or space, optional." );
text += separatorline;
text += string.Format( linetemplate, "#", "Digit or space, optional. If this position is blank in the mask, it will be" );
text += string.Format( linetemplate, " ", "rendered as a space in the Text property. Plus (+) and minus (-) signs allowed." );
text += separatorline;
text += string.Format( linetemplate, "L", "Letter, required. Restricts input to the ASCII letters a-z and A-Z." );
text += string.Format( linetemplate, " ", "This mask element is equivalent to [a-zA-Z] in regular expressions." );
text += separatorline;
text += string.Format( linetemplate, "?", "Letter, optional. Restricts input to the ASCII letters a-z and A-Z." );
text += string.Format( linetemplate, " ", "This mask element is equivalent to [a-zA-Z]? in regular expressions." );
text += separatorline;
text += string.Format( linetemplate, "&", "Character, required. Any non-control character." );
text += string.Format( linetemplate, " ", "If ASCII only is set, this element behaves like the \"A\" element." );
text += separatorline;
text += string.Format( linetemplate, "C", "Character, optional. Any non-control character." );
text += string.Format( linetemplate, " ", "If ASCII only is set, this element behaves like the \"a\" element." );
text += separatorline;
text += string.Format( linetemplate, "A", "Alphanumeric, required. If ASCII only is set, the only characters it will accept" );
text += string.Format( linetemplate, " ", "are the ASCII letters a-z and A-Z and numbers. This mask element behaves like" );
text += string.Format( linetemplate, " ", "the \"&\" element." );
text += separatorline;
text += string.Format( linetemplate, "a", "Alphanumeric, optional. If ASCII only is set, the only characters it will accept" );
text += string.Format( linetemplate, " ", "are the ASCII letters a-z and A-Z and numbers. This mask element behaves like" );
text += string.Format( linetemplate, " ", "the \"C\" element." );
text += separatorline;
text += string.Format( linetemplate, ".", "Decimal placeholder." );
text += separatorline;
text += string.Format( linetemplate, ",", "Thousands placeholder." );
text += separatorline;
text += string.Format( linetemplate, ":", "Time separator." );
text += separatorline;
text += string.Format( linetemplate, "/", "Date separator." );
text += separatorline;
text += string.Format( linetemplate, "$", "Currency symbol." );
text += separatorline;
text += string.Format( linetemplate, "<", "Shift down. Converts all characters that follow to lowercase." );
text += separatorline;
text += string.Format( linetemplate, ">", "Shift up. Converts all characters that follow to uppercase." );
text += separatorline;
text += string.Format( linetemplate, "|", "Disable a previous shift up or shift down." );
text += separatorline;
text += string.Format( linetemplate, "\\", "Escape. Escapes a mask character, turning it into a literal." );
text += string.Format( linetemplate, " ", "\"\\\\\" is the escape sequence for a backslash." );
text += separatorline;
text += string.Format( linetemplate, "All other", "Literals. All non-mask elements will appear as themselves within MaskedTextBox." );
text += string.Format( linetemplate, "characters", "Literals always occupy a static position in the mask at run time, and cannot be" );
text += string.Format( linetemplate, " ", "moved or deleted by the user." );
text += "\u2514" + new string( '\u2500', 12 ) + "\u2534" + new string( '\u2500', 82 ) + "\u2518\n\n";
text += "Source: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.maskedtextbox.mask\n";
return text;
}
public static string MessageBoxButtons( )
{
return string.Join( ";", System.Enum.GetNames( typeof( System.Windows.Forms.MessageBoxButtons ) ) );
}
public static string MessageBoxIcons( )
{
return string.Join( ";", System.Enum.GetNames( typeof( System.Windows.Forms.MessageBoxIcon ) ) );
}
public static string MessageBoxOptions( )
{
return string.Join( ";", System.Enum.GetNames( typeof( System.Windows.Forms.MessageBoxOptions ) ) );
}
public static string Properties( object obj )
{
System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>( );
System.Reflection.PropertyInfo[] propertyinfo = obj.GetType( ).GetProperties( );
for ( int i = 0; i < propertyinfo.Length; i++ )
{
string propertyname = propertyinfo[i].Name;
string propertyvalue = obj.GetType( ).GetProperty( propertyinfo[i].Name ).GetValue( obj: obj, index: null ).ToString( );
result.Add( string.Format( "{0} = {1}", propertyname, propertyvalue.ToString( ) ) );
}
result.Sort( );
return string.Join( System.Environment.NewLine, result.ToArray( ) );
}
public static System.Collections.Generic.List<string> SpecialFolders( )
{
System.Collections.Generic.List<string> specialfolders = new System.Collections.Generic.List<string>( );
foreach ( System.Environment.SpecialFolder sf in typeof( System.Environment.SpecialFolder ).GetEnumValues( ) )
{
if ( !specialfolders.Contains( sf.ToString( ) ) )
{
specialfolders.Add( sf.ToString( ) );
}
}
specialfolders.Sort( );
return specialfolders;
}
public static string ToolTipIcons( )
{
return string.Join( ";", System.Enum.GetNames( typeof( System.Windows.Forms.ToolTipIcon ) ) );
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public class Localization
{
public static string Caption( uint resource )
{
return Load( "user32.dll", resource, "" ).Replace( "&", "" );
}
public static string CaptionsTable( )
{
string text = "Localized Captions Table";
text += "\n" + new string( '\u2550', text.Length ) + "\n\n";
string separatorline = "\u251C" + new string( '\u2500', 10 ) + "\u253C" + new string( '\u2500', 34 ) + "\u2524\n";
string linetemplate = "\u2502 {0,8} \u2502 {1,-32} \u2502\n";
text += "\u250C" + new string( '\u2500', 10 ) + "\u252C" + new string( '\u2500', 34 ) + "\u2510\n";
text += string.Format( linetemplate, "Resource", "Caption" );
text += "\u255E" + new string( '\u2550', 10 ) + "\u256A" + new string( '\u2550', 34 ) + "\u2561\n";
for ( uint i = 800; i < 1000; i++ )
{
string caption = Load( "user32.dll", i, "" ).Replace( "&", "" );
if ( !string.IsNullOrWhiteSpace( caption ) )
{
if ( i != 800 )
{
text += separatorline;
}
text += string.Format( linetemplate, i, caption );
}
}
text += "\u2514" + new string( '\u2500', 10 ) + "\u2534" + new string( '\u2500', 34 ) + "\u2518\n\n";
text += "Code to retrieve localized captions by Martin Stoeckli;\n";
text += "http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources\n";
return text;
}
[System.Runtime.InteropServices.DllImport( "kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto )]
private static extern System.IntPtr GetModuleHandle( string lpModuleName );
// Code to retrieve localized captions by Martin Stoeckli
// http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources
/// <summary>
/// Searches for a text resource in a Windows library.
/// Sometimes, using the existing Windows resources, you can make your code
/// language independent and you don't have to care about translation problems.
/// </summary>
/// <example>
/// btnCancel.Text = Load("user32.dll", 801, "Cancel");
/// btnYes.Text = Load("user32.dll", 805, "Yes");
/// </example>
/// <param name="libraryName">Name of the windows library like "user32.dll"
/// or "shell32.dll"</param>
/// <param name="ident">Id of the string resource.</param>
/// <param name="defaultText">Return this text, if the resource string could
/// not be found.</param>
/// <returns>Requested string if the resource was found,
/// otherwise the <paramref name="defaultText"/></returns>
public static string Load( string libraryName, uint ident, string defaultText )
{
System.IntPtr libraryHandle = GetModuleHandle( libraryName );
if ( libraryHandle != System.IntPtr.Zero )
{
System.Text.StringBuilder sb = new System.Text.StringBuilder( 1024 );
int size = LoadString( libraryHandle, ident, sb, 1024 );
if ( size > 0 )
return sb.ToString( );
}
return defaultText;
}
[System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto )]
private static extern int LoadString( System.IntPtr hInstance, uint uID, System.Text.StringBuilder lpBuffer, int nBufferMax );
}
[System.Runtime.InteropServices.ComVisible( false )]
public class ProgramInfo
{
private static string _path = System.Reflection.Assembly.GetAssembly( typeof( RobvanderWoude.DialogBoxes ) ).Location;
public static string Path
{
get
{
return _path;
}
}
private static System.Diagnostics.FileVersionInfo _progfileversioninfo = System.Diagnostics.FileVersionInfo.GetVersionInfo( _path );
public static string FileName
{
get
{
return System.IO.Path.GetFileName( _progfileversioninfo.FileName );
}
}
public static string FileVersion
{
get
{
return _progfileversioninfo.FileVersion;
}
}
public static string Comment
{
get
{
return _progfileversioninfo.Comments;
}
}
public static string Copyrights
{
get
{
return _progfileversioninfo.LegalCopyright;
}
}
public static void CheckUpdate( )
{
System.Diagnostics.Process.Start( "https://www.robvanderwoude.com/dialogboxesdll.php?ver=" + FileVersion );
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public class Validate
{
public static System.Drawing.Color ColorName( string testcolor, System.Drawing.Color defaultcolor )
{
if ( System.Enum.TryParse( testcolor, true, out System.Drawing.Color color ) )
{
return color;
}
else
{
ValidationErrors.Add( "ColorName", string.Format( "\"{0}\" is not recognized as a valid color name", testcolor ) );
return defaultcolor;
}
}
public static System.Drawing.Color ColorRGB( string testrgb, System.Drawing.Color defaultcolor )
{
System.Drawing.Color result = defaultcolor;
bool found = false;
string[] RGB = testrgb.Split( ',' );
byte R = System.Convert.ToByte( System.Convert.ToInt32( RGB[0] ).LimitToRange( 0, 255 ) );
byte G = System.Convert.ToByte( System.Convert.ToInt32( RGB[1] ).LimitToRange( 0, 255 ) );
byte B = System.Convert.ToByte( System.Convert.ToInt32( RGB[2] ).LimitToRange( 0, 255 ) );
foreach ( System.Drawing.Color color in System.Enum.GetValues( typeof( System.Drawing.Color ) ) )
{
if ( color.R == R && color.G == G && color.B == B )
{
result = color;
found = true;
break;
}
}
if ( !found )
{
ValidationErrors.Add( "ColorRGB", string.Format( "\"{0}\" is not recognized as a valid RGB value", testrgb ) );
}
return result;
}
public static FontCharSet FontCharSet( string testcharset )
{
if ( System.Enum.TryParse( testcharset, true, out FontCharSet charset ) )
{
return charset;
}
else
{
ValidationErrors.Add( "FontCharSet", string.Format( "\"{0}\" is not recognized as a valid FontCharSet", testcharset ) );
return (FontCharSet) 0;
}
}
public static System.Drawing.FontFamily FontFamily( string fontfamilyname, System.Drawing.FontFamily defaultfontfamily, bool monospaced = false )
{
try
{
if ( System.Enum.GetNames( typeof( System.Drawing.FontFamily ) ).Contains( fontfamilyname, System.StringComparer.InvariantCultureIgnoreCase ) )
{
System.Drawing.FontFamily suggestedfontfamily = new System.Drawing.Text.InstalledFontCollection( ).Families.Where( f => f.Name.Equals( fontfamilyname ) ).First( );
bool ismonospaced = suggestedfontfamily.IsFixedPitch( );
if ( ismonospaced == monospaced )
{
return suggestedfontfamily;
}
else
{
if ( monospaced )
{
ValidationErrors.Add( "FontFamily", string.Format( "\"{0}\" is not a fixed pitch font family, but fixed pitch was requested", fontfamilyname ) );
}
else
{
ValidationErrors.Add( "FontFamily", string.Format( "\"{0}\" is a fixed pitch font family, but fixed pitch was not requested", fontfamilyname ) );
}
return defaultfontfamily;
}
}
}
catch ( System.Exception e )
{
ValidationErrors.Add( "FontFamily", string.Format( "Error while trying to make sense of the specified font family name: " + e.Message ) );
}
ValidationErrors.Add( "FontFamily", string.Format( "\"{0}\" is not recognized as a valid font family name", fontfamilyname ) );
return defaultfontfamily;
}
public static System.Drawing.FontStyle FontStyle( string fontstyle )
{
if ( System.Enum.TryParse( fontstyle, true, out System.Drawing.FontStyle style ) )
{
return style;
}
else
{
ValidationErrors.Add( "FontStyle", string.Format( "\"{0}\" is not recognized as a valid FontStyle", fontstyle ) );
return System.Drawing.FontStyle.Regular;
}
}
public static System.Collections.SortedList ValidationErrors = new System.Collections.SortedList( );
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public class IconExtractor
{
// Code to extract icons from Shell32.dll by Thomas Levesque
// http://stackoverflow.com/questions/6873026
public static System.Drawing.Icon Extract( string file, int number, bool largeIcon )
{
System.IntPtr large;
System.IntPtr small;
ExtractIconEx( file, number, out large, out small, 1 );
try
{
return System.Drawing.Icon.FromHandle( largeIcon ? large : small );
}
catch
{
return null;
}
}
[System.Runtime.InteropServices.DllImport( "Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling = true, CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall )]
private static extern int ExtractIconEx( string sFile, int iIndex, out System.IntPtr piLargeVersion, out System.IntPtr piSmallVersion, int amountIcons );
}
[System.Runtime.InteropServices.ComVisible( false )]
public class PrinterSelectBox
{
public const int defaultheight = 220;
public const int defaultwidth = 400;
private static System.Windows.Forms.Label _commentfield;
public static System.Windows.Forms.Label CommentField
{
get
{
return _commentfield;
}
set
{
_commentfield = value;
}
}
private static System.Windows.Forms.Form _form;
public static System.Windows.Forms.Form Form
{
get
{
return _form;
}
set
{
_form = value;
}
}
private static System.Windows.Forms.ComboBox _printersdropdown;
public static System.Windows.Forms.ComboBox PrintersDropDown
{
get
{
return _printersdropdown;
}
set
{
_printersdropdown = value;
}
}
private static System.Collections.Generic.List<string[]> _printerslist;// = new System.Collections.Generic.List<System.String[]>( );
public static System.Collections.Generic.List<string[]> PrintersList
{
get
{
return _printerslist;
}
set
{
_printerslist = value;
}
}
private static string _selectedprinterattimeout = string.Empty;
public static string SelectedPrinterAtTimeout
{
get
{
return _selectedprinterattimeout;
}
set
{
_selectedprinterattimeout = value;
}
}
private static System.Windows.Forms.Label _statusfield;
public static System.Windows.Forms.Label StatusField
{
get
{
return _statusfield;
}
set
{
_statusfield = value;
}
}
private static System.Timers.Timer _timer;
public static System.Timers.Timer Timer
{
get
{
return _timer;
}
set
{
_timer = value;
}
}
private static bool _timeoutelapsed = false;
public static bool TimeoutElapsed
{
get
{
return _timeoutelapsed;
}
set
{
_timeoutelapsed = value;
}
}
private static System.Windows.Forms.Label _typefield;
public static System.Windows.Forms.Label TypeField
{
get
{
return _typefield;
}
set
{
_typefield = value;
}
}
private static System.Windows.Forms.Label _wherefield;
public static System.Windows.Forms.Label WhereField
{
get
{
return _wherefield;
}
set
{
_wherefield = value;
}
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public class RadioButtonBox
{
public const int defaultheight = 320;
public const int defaultwidth = 480;
private static System.Windows.Forms.Form _form;
public static System.Windows.Forms.Form Form
{
get
{
return _form;
}
set
{
_form = value;
}
}
private static System.Windows.Forms.GroupBox _groupbox;
public static System.Windows.Forms.GroupBox GroupBox
{
get
{
return _groupbox;
}
set
{
_groupbox = value;
}
}
private static string _selecteditemattimeout = string.Empty;
public static string SelectedTextAtTimeout
{
get
{
return _selecteditemattimeout;
}
set
{
_selecteditemattimeout = value;
}
}
private static System.Timers.Timer _timer = null;
public static System.Timers.Timer Timer
{
get
{
return _timer;
}
set
{
_timer = value;
}
}
private static bool _timeoutelapsed = false;
public static bool TimeoutElapsed
{
get
{
return _timeoutelapsed;
}
set
{
_timeoutelapsed = value;
}
}
}
}
[System.Runtime.InteropServices.ComVisible( false )]
public static class ExtensionMethods
{
public static int LimitToRange( this int value, int inclusiveMinimum, int inclusiveMaximum )
{
// Extension by "dtb" on StackOverflow.com:
// https://stackoverflow.com/a/3176628
if ( value < inclusiveMinimum )
{
return inclusiveMinimum;
}
if ( value > inclusiveMaximum )
{
return inclusiveMaximum;
}
return value;
}
public static float LimitToRange( this float value, float inclusiveMinimum, float inclusiveMaximum )
{
if ( value < inclusiveMinimum )
{
return inclusiveMinimum;
}
if ( value > inclusiveMaximum )
{
return inclusiveMaximum;
}
return value;
}
public static bool IsFixedPitch( this System.Drawing.FontFamily value )
{
System.Drawing.Font font = new System.Drawing.Font( value, 12, System.Drawing.FontStyle.Regular );
return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", font ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", font ) );
}
public static bool IsFixedPitch( this System.Drawing.Font value )
{
// Inspired by a tip from Hans passant
// https://stackoverflow.com/q/21965321
return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", value ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", value ) );
}
}
public enum ConsoleColors : int
{
Black = 0x000000,
DarkBlue = 0x000080,
DarkGreen = 0x008000,
DarkCyan = 0x008080,
DarkRed = 0x800000,
DarkMagenta = 0x800080,
DarkYellow = 0x808000,
Gray = 0xC0C0C0,
DarkGray = 0x808080,
Blue = 0x0000FF,
Green = 0x00FF00,
Cyan = 0x00FFFF,
Red = 0xFF0000,
Magenta = 0xFF00FF,
Yellow = 0xFFFF00,
White = 0xFFFFFF
}
public enum FontCharSet : byte
{
ANSI = 0,
Default = 1,
Symbol = 2,
Mac = 77,
ShiftJIS = 128,
Hangeul = 129,
Johab = 130,
GB2312 = 134,
ChineseBig5 = 136,
Greek = 161,
Turkish = 162,
Hebrew = 177,
Arabic = 178,
Baltic = 186,
Russian = 204,
Thai = 222,
EastEurope = 238,
OEM = 255,
}
public enum PrinterCategory
{
All,
Local,
Network,
Physical,
Virtual
}
public enum WMIPrinterStatus
{
Other = 1,
Unknown = 2,
Idle = 3,
Printing = 4,
Warmup = 5,
StoppedPrinting = 6,
Offline = 7,
Paused = 8,
Error = 9,
Busy = 10,
NotAvailable = 11,
Waiting = 12,
Processing = 13,
Initialization = 14,
PowerSave = 15,
PendingDeletion = 16,
IOActive = 17,
ManualFeed = 18
}
}
page last modified: 2024-04-16; loaded in 0.0300 seconds