1
Reply

Windows Forms app with no forms shown

Simon Edkins

Simon Edkins

Oct 3 2012 2:17 PM
1.3k
Hi,

I am building a faceless application that will be shell-called from another program, with some arguments passed in. Its primary purpose is to read a value from an electronic balance (serial communication), store the value in a db, and quit.

I started with a console app, which runs a separate thread to read the serial port and display the result with Console.WriteLine. But I want the result passed back to the main thread in a variable, for further processing. The usual way to do this in a Forms application is set up a delegate to respond to the DataReceived event, but apparently it is not possible to set up or invoke a delegate in a console app.

So I next tried a forms application, but calling the Application.Run method (in Main) without arguments, so no form is opened. Starting slowly, I just wanted it to launch, accepting two arguments, write a text file, and quit. But not only is a file not written (the exact same six lines I used in a console app, so I know it works), the app doesn't even seem to quit reliably (that is, I'll go back into Vis Studio, make a change and build it again, only to get the error message that it can't be written because it's in use by another process (and I have to use the TM to force quit the process)).

So my question is: what am I missing here? Is it actually possible to have a threaded console app with delegates, or is the faceless forms app the way to go, and if so, what am I doing wrong in the following code? It compiles fine, but doesn't appear to do anything. Any pointers to working examples of either approach would be welcome.

Thanks,

Simon

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Windows.Forms;
using
System.Media;
namespace
Balance_Reader
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[
STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Application.Run();
WriteAFile(args[0], args[1]);
Application.Exit();
}
static void WriteAFile(string Path, string FileName)
{
string ThePath = Path + @"\" + FileName + ".txt";
SystemSounds.Beep.Play();
System.IO.
StreamWriter objFile = new System.IO.StreamWriter(ThePath);
objFile.WriteLine(
"This is the first line");
objFile.WriteLine(
"This is the second line");
objFile.Close();
objFile.Dispose();
}
}
}

Answers (1)