C# Programming

Child Pages

Binding
ContentsObservableCollectionSearching For And Selecting A Particular ElementObtaining The Current DataContext For A UI ElementThe best tutorial of Binding in WPF that I’ve found is here. It includes a project download which is great for binding that works out-of-the-box, which you can then hack/adjust to your own needs. ObservableCollection The ObservableCollection()  class is used plenty when it … Continue reading Binding
Closing Your Application
ContentsWPFWPF A common way to close the application is to use the following command: Common Way To Shutdown WPF Applications C# Application.Current.Shutdown(); 1 Application.Current.Shutdown(); However, although your main form will close, this can sometimes leave remnants (e.g. processes) running in the background. If this is happening, I have found that the following way exits everything: … Continue reading Closing Your Application
Detecting Key Presses
ContentsWinFormsWPFNon-Binding MethodWinForms Use the following code to detect a key press when focus is on a particular object. Note: There is different syntax for WPF. Detecting A Key Press In WinForms C# TextBox tb = new TextBox(); // Assign a new event handler tb.KeyDown += new KeyEventHandler(tb_KeyDown); // The event handler private void tb_KeyDown(object sender, … Continue reading Detecting Key Presses
Going From WinForms To WPF
The layout of what is traditionally known as the “forms” is described in an entirely new way, using XAML rather than the C# langauge. This makes it rather similar to HTML. The forms also look plenty more modern, with things such as nice rounded corners on the controls and cool colour themes. Form objects no … Continue reading Going From WinForms To WPF
Graph Drawing
ContentsNPlotOxyPlotSmoothing The LinesRadChartSome QuickStart RadChart ExamplesZedGraphSome QuickStart ZedGraph ExamplesNPlot Supported Platforms: .NET (WinForms) Dimension Support : 2D User Control Interface: ? Data Binding Support: ? Tutorials: 1/5 User Base: 1/5 Licnese/Price: Open Source Graphing program that hasn’t had much development recently, but still relatively powerful. Nice interactive scaling/scrolling features of graphs, making it easy to … Continue reading Graph Drawing
How To Access Serial Ports In C#
The pre-installed Visual Studio C# class for manipulating serial ports in C# is found in the following namespace: The SerialPort Class C // The class for manipulating serial ports in C# System.IO.Ports.SerialPort 12 // The class for manipulating serial ports in C#System.IO.Ports.SerialPort To get a string list of the current active COM ports on the … Continue reading How To Access Serial Ports In C#
Redirecting The Command-line To A Text Block
It involves inheriting from the StringWriter class, and overwriting it’s WriteLine function with your own code that writes the text to the text block (or any other text-capable object), rather than Windows writing it to the system console (whatever that may be). Note that this code is suitable for passing into functions that require a … Continue reading Redirecting The Command-line To A Text Block
Threading
ContentsUpdating The UI From Another TaskLockingQueuesUpdating The UI From Another Task In WPF, the “Dispatcher” is the way to call a function that belongs to a class in one thread from another thread. As long as the class you are calling supports the Dispatcher object (all UI classes such as Window  do) , you can use … Continue reading Threading
Timers
The System.Windows.Threading.DispatcherTimer  dispatch timer is used when you only want a single event. It fires of an event, and DOES NOT create a new thread. However, this means that the timer function will not run while other code in the  same thread is executing. The System.Timers.Timer  timer creates a new thread for the timer expired event. This … Continue reading Timers
Using InstallSheild
ContentsOverviewCreating A Single setup.exeVersion NumbersUpgrading From Older VersionsUsing The Command-LineNon-optional OptionsOptional OptionsLaunching Program On InstallOverview This page is all about using InstallShield with Visual Studio projects to create installable setup files for the user to use. Creating A Single setup.exe For smaller projects and things that will be downloaded over the internet, you’ll most likely … Continue reading Using InstallSheild
Windows Office Application Interface
ContentsTutorialText Boxes:TablesManipulating The CursorBreaks (Line, Page, …)You can use C# to manipulate Microsoft Office programs such as Word and Excel. You can open, create, edit and do essentially everything you can do in the programs natively using instead C# (albeit a little longer…) and libraries provided by Microsoft. A good tutorial on the Word API … Continue reading Windows Office Application Interface

String Manipulation

<string type>.IndexOf – Searchs for a particuler character within a string, and returns the position of the first instance found. Can specify where in the string to start looking, as well as how many characters to look through

Convert.To<type> – Converts back and forth from many standard types, including integers and strings

There is a great cheat sheet by John Sheehan which explains string manipulation in the .NET language. Unfortunately, it can no longer be found on his site. See the link below to download.

[wpfilebase tag=file id=6 /]

Removing Characters From A String

<string type>.Remove – Removes characters from a string, starting at a specified location. Note that this creates a new string with chosen characters removed, it DOES NOT touch the original string! This is a common mistake for people to make, and results in nothing happening to the string.

Converting To Hex

Use the Convert.ToString()  class to convert to a hexadecimal string. The case of the format specifier (i.e. ‘x’ or ‘X’), determines whether the alphabetical characters in the hex output (A-F) will be in lower-case or in upper-case.

Populating A ComboBox From An Enumeration

Populating a combo box from an enumeration can save heaps of typing and manual work to enter each item individually. It is done easily with the one line of code below:

You can also use the actual value of an Enum rather than it’s name by casting it to an int.

Iterating Through An Enumeration

Use the following code:

Running .NET On Non-Windows Platforms

There is a popular “cross platform, open source, .NET development framework” called Mono. It is an open source implementation of the .NET framework which can run on a number of devices including Linus, Mac OS, Windows (of course), and even the RaspberryPi!

Signal Processing

The Math.Net project contains the “Neodym” library for signal processing in C#. See the Signal Processing page for more information.

Rounding

The Math library (Math.<some function>) supports basic rounding. However, here is a trick to round to any specified value. You basically divide the number by the precision (the number to want to round to, e.g. 0.1, 0.25, 5 e.t.c), then use standard rounding on the result, and lastly multiply the rounded number by the precision to get the answer.

You can also preform variable precision rounding with an offset.

Profiling And Performance Tuning

To programs to do this are SlimTune and EQATEC.

Command-Line Parsers

Command-line parsers are a good way for user-program interaction and well as computer-computer communication. There are quite a few free and opensource C# Command-Line Parsers out there. Their core functionality is similar to the C-based linux getopt() command, but incorporate the powerful functionality of the .NET language. Most use inline lambda notation to create the equivalent of call-back functions when registering the parameters.

Command Line Parser Library

Author: GSSCoder

Author’s Link: https://github.com/gsscoder/commandline

CodePlex: http://commandline.codeplex.com/

NuGet: “install-package CommandLineParser” (latest stable), “install-package CommandLineParser -pre” (latest release)

This library has had a continuously updated API since 2005. Parses commands in the “–age 50” style. Requires the parameters to registered with a custom class at build time.

Does not support an initial keyword that determines the nature of the following parameters (similar to calling a particular program).

cmdline

Author: Ron Jacobs

Author’s Link: http://code.msdn.microsoft.com/Command-Line-Parser-Library-a8ba828a

NuGet: “install-package cmdline”

NDesk.Options

Author: NDesk

Author’s Link:

NuGet:

This one can support multiple commands, with the additional library ManyConsole. NDesk.Options replaced the now obsolete Mono.Options library, and it is include in the Mono 2.0 package.

ManyConsole

Author: https://github.com/fschwiet

Author’s Link: https://github.com/fschwiet/ManyConsole

NuGet: install-package ManyConsole

This library supports multiple commands, which is useful if you want to use the command-line style for communication between two computers/microcontrollers. It uses the NDesk.Options library. In my opinion, ManyConsole is hard to use, and requires all the commands/parameters to be created at compile time as classes.

Microsoft Office Program Manipulation With C#

You can manipulate Microsoft Office applications quite easily within the .NET framework (which includes C#). See the following page I wrote for more information.

=> Windows Office Application Interface

Installing Third-Party Libraries

I recommend a package manager like NuGet is used to install third-party libraries/packages whenever possible. NuGet allows you to select a pre-compiled third-part library from a large online database and then install it into a Visual Studio project at the click of a button. It also removes a library just as quickly. The image below shows the NuGet package management screen

Other Resources

If you have the money, you can buy the MS Word component Spire.Doc from E-IceBlue. It provides an API to easily create and manipulate Word documents in an easier manner than with Microsoft’s standard library.