Monday, May 31, 2010

Emit a Beep

With the function Console.Beep() our application does not suddenly turn into a DJ - program, but this function can emit beep tones using the internal or, if plugged in, external speakers.
A call without parameters creates a "standard beep", as parameters the pitch and Hertz and the duration in milliseconds available.
Console.Beep() is only avaible from .Net 2.0 and upwards.
The operating systems Windows 98 - Windows ME cannot interpret the parameters.

Query Currently Active Form

In my applications I sometimes want to know, whether a specific form has the focus in the moment, meaning it is active at this time. Or, for applications with only one form, whether the whole application has the focus.
With this the current form is adressed. The property Focused checks, whether the form has focus.
The following little sample code can for example be copied in the Tick event of a timer and switches periodically the background color of the form, depending whether the form is active or not:
private void timer1_Tick(object sender, EventArgs e)
    if (this.Focused)
        this.BackColor = Color.Red; // red if form has focus
        this.BackColor = Color.Green; // green otherwise

Saturday, May 29, 2010

Add Controls During Runtime

When creating advanced applications, one will reach the point at which one is not satisfied with creating static forms only but wants to add controls dynamically during runtime.
Controls are basically just variables, e.g. of type Button, TextBox etc ... Like other variables they can also be initialized at runtime and then just have to be added to the form.
The following hopefully self-explaining code adds a new button to the form:
Button NewButton = new Button(); // initialize variable of type button
NewButton.Width = 100; // set width
NewButton.Height = 20; // set height
NewButton.Left = 10; // distance from left border
NewButton.Top = 50; // distance from top border
NewButton.Text = "Klick mich"; // label of the button
this.Controls.Add(NewButton); // add the new button to the form

In the last line of code the button variable is appended to the list this.Controls, which contains all controls of the form. It it is not added to this list, the control will also not be shown.

Wait for a While

In this post I want to show how to make the C# application wait for some time and resume its run only after the elapse of this time This purpose serves the function System.Threading.Thread.Sleep().
It stops the current thread to wait for the time specified as parameter (in milliseconds).
A thread is kind of a subprocess of a process. A C# application is started in its own process, but since there are of course other running processes on the operating system, the operating system switches between these continously, the current active one is always executed.
Now in our C# application we can create multiple threads.
These seem to run independent of each other, if the application process gets the focus it switches itself between the different threads, so we get an impression of parallel execution. A "normal" Windows Forms - Application consists of only one thread though, so that the following code halts the whole program for 1 second:

Simulate Key Press

For simulating key strokes in C# there is aswell an easy function.
The class SendKeys provides corresponding possibilites.
The functions Send() and SendWait() exist. Both functions expect a string as a parameter, which is then send to the active program, as if the user had pressed that key.
SendWait() waits in contrast to Send() for the procession of the input.
The following code can for example be copied in the Click - Event of a button.
If the code is executed, the program waits for 3 seconds, the user can switch to a different program (e.g. a chat program - do not abuse, haha) and the application sends the message "WICHTIG!" 100 times:
for (int i = 0; i < 100; i++)
    SendKeys.Send("WICHTIG! \n");

"\n" adds a line break to the text, but key presses of special keys like the Enter key can also be simulated, Enter for example with "{ENTER}" (as a string, meaning with quotation marks like a normal text).

Friday, May 28, 2010

End C# Application

To exit the own C# application via code is easy, some may not know the command though.
Therefor, you get this as today's post.
In Windows Forms - Applications the command
prompts the program to exit.
In Console Applications this command is not avaible though. In such it is possible to call the command return in the main function void Main(), to close the console.

Thursday, May 27, 2010

Shutdown the Computer

To shut the computer down by a C# - program, we just call the native to Windows program "shutdown".
When entering this command in the command prompt (cmd.exe), e.g. with the parameters shutdown -s -t 60, the computer will shut down after the elapse of 60 seconds.
Entering this command actually calls the program "shutdown.exe", which is located in the system32 folder.
. To start an external programm we use the function System.Diagnostics.Process.Start(), like described in a previous post.
In the program we now can for example enter
System.Diagnostics.Process.Start(System.Environment.SystemDirectory + "\\shutdown.exe", "-s -t 60");

When executing this code, a message will pop up saying the computer is shutting down in 60 seconds.
Finally, some further possible parameters for "shutdown.exe":
  • -l: Log out
  • -s: Shutdown
  • -r: Restart
  • -a: Abort
  • -t XX: Time
  • -c: Prints a comment von shutting down
  • -f: Forces the shutdown (closes all open programs)

Start Process With C#

With the .Net Framework it is pretty easy to start an external process / programm.
The command System.Diagnostics.Process.Start() starts the exe file, which is given as argument.
To start notepad for example, enter the following:
System.Diagnostics.Process.Start(System.Environment.SystemDirectory + "\\notepad.exe");

System.Environment.SystemDirectory returns the path to the system directionary (in my case, C:\Windows\system32).
Furthermore, there are two backslashes in front of \\notepad.exe, because "\" has to be "escaped".
A single "\" alone would make the compiler view "\n" as a special character, "\\" tell it, that we really mean an actual "\".
The function Process.Start() can accept also other parameters beneath the path, with which the programm will be called.
If in the above example notepad is to be started with opening the file Beispiel.txt, which sits on my desktop, the command has to be changed as follows:
System.Diagnostics.Process.Start(System.Environment.SystemDirectory + "\\notepad.exe", "C:\\Users\\Oliver\\Desktop\\Beispiel.txt");

Wednesday, May 26, 2010

Start Application With Administrative Rights on Windows Vista / 7

In the Windows versions Vista and 7 the User Account Control (UAC) determines, that the currently logged in user, even if he is administrator, is not treated as such. Therefor, when trying to perform actions which might affect the operating system, the probably well known dialog asking for administrative permissions is shown. For us this means, that applications, even when run by the administrator, do not run as administrator and cannot perform actions which require higher permissions.
To equip a program with these higher permissions, we add in the .Net development environment an application manifest (Project - Add New Element - Application Manifest) The content should look somewhat like follows:

We are interested in the line < requestedExecutionLevel level="asInvoker" uiaccess="false">. For requestedExecutionLevel we can chose asInvoker, highestAvailable or requireAdministrator eingetragen werden.
When selecting requireAdministrator, we see at program start the known dialog asking for administrative permissions, after answering with yes, the application is equipped with these rights.

To equip the application without such an application manifest, see this post.

Tuesday, May 25, 2010

Show Application Not as a Task but as a Process

To tell the operating system to not show an application as a Task in the task manager but as a process, it suffices to "hide" the application literally.
Let us consider a Windows-Forms application as example. If we change the property Visible of the form to false, e.g. by
this.Visible = false;
(with this always the current form is meant), the current form becomes invisible and therefor is only listed as a process in the task manager.
While running, e.g. when clicking on a button, this code can be run without problems.
A bit harder is it, if the form is to be hidden directly from start on.
In Form1_Load the code does not affect the behaviour, since after this function the function Show() of the form is called and the form is shown again.
In my opinion the best method to hide the form from start on is to override void OnShown(EventArgs e) of the form, which is called in the call of Show().
The complete declaration of the function is:
protected override void OnShown(EventArgs e)
    this.Visible = false;
base.OnShown(e); is added by the compiler automatically, this line prompts the call of OnShown() of the father class Form.