Move a form that doesn't have a titlebar

Here's how to move a form that doesn't have a titlebar:

using System;

using System.Runtime.InteropServices; using System.Windows.Forms;

namespace MoveFormWithoutTitlebar { public partial class Form1 : Form {

    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HT_CAPTION = 0x2;

    [DllImportAttribute("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd,
                     int Msg, int wParam, int lParam);

    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();


    public Form1() {
        InitializeComponent();
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e) {
        if (e.Button == MouseButtons.Left) {
            ReleaseCapture();
            SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        }
    }
}

}

Create an About form

How to programmatically create an About form and have it appear centered in a 1000x700 pixel MainForm:

            about = new Form();
        about.MaximizeBox = false;
        about.FormBorderStyle = FormBorderStyle.None;
        about.Size = new Size(400,300);
        about.TopMost = true;           

        Label lblAbout = new Label();
        lblAbout.Text = "About";
        lblAbout.Font = new Font("Verdana",14);
        lblAbout.AutoSize = true;
        int lblAboutLeft = (about.Width - lblAbout.Width)/2;            
        lblAbout.Left = about.Left + lblAboutLeft + 9;
        about.Controls.Add(lblAbout);

        Button btnClose = new Button();
        btnClose.Text = "&Close";           
        btnClose.Width = 50;
        btnClose.Location = new Point(btnClose.Left + 347, btnClose.Top + 275);
        about.Controls.Add(btnClose);

        PictureBox picProgrammer = new PictureBox();
        picProgrammer.AutoSize = true;          
        picProgrammer.Image = Image.FromFile(".\\Resources\\Images\\bryanCircle.PNG");
        about.Controls.Add(picProgrammer);
        picProgrammer.Left += 2;
        picProgrammer.Top += 2;

        TextBox tb = new TextBox();
        tb.Font = new Font("Verdana",10);
        tb.Multiline = true;
        tb.ScrollBars = ScrollBars.Vertical;
        tb.Height = about.Height - lblAbout.Height - btnClose.Height  - 7;
        tb.Width = about.Width - picProgrammer.Width - 8;
        about.Controls.Add(tb);
        tb.Top = lblAbout.Top + lblAbout.Height + 2;
        tb.Left = picProgrammer.Left + picProgrammer.Width;
        string readData = File.ReadAllText(".\\Resources\\Texts\\about.txt");
        tb.Text = readData;

        about.Show();
        int left = (this.Width - about.Width)/2;
        left += iMainFormLeft;
        int top = (this.Height - about.Height)/2;
        top += iMainFormTop;
        about.Location = new Point(left, top);


        btnClose.Click += new EventHandler(btnClose_Click);

My preferred FormLoad()

        void MainFormLoad(object sender, EventArgs e)
    {
        blnShowingAbout = false;
        this.DoubleBuffered = true;
        this.Size = new Size(1000,700);
        this.FormBorderStyle = FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.Text = "\"Proofy\", the Proofreader's App — Wm. Miller Services ©2017";
        this.CenterToScreen();      

    }               

Fade C# Form Gradually

        void showClosingMsgInTitlebarThenExit()
    {
        this.Text = "Now closing the \"Proofy\" app...";
        System.Threading.Thread.Sleep(750);
        for(Double d = 1.00; d > 0.00; d -= 0.025)
        {               
            this.Opacity = d;
            System.Threading.Thread.Sleep(55);
        }
        Environment.Exit(0);

    }

upload file to server using C#

The following code sample shows uploading of text file "test.txt" in the app's directory to "ftp://kyrathasoft.com/testbed/test.txt" using login info bigdaddy@kyrathasoft.com and password "shitstorm":

namespace UploadExample {

class Program {

    static void Main(string[] args) {




        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://kyrathasoft.com/testbed/test.txt");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential("bigdaddy@kyrathasoft.com", "shitstorm");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader("test.txt");
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();

        Console.WriteLine("Press a key to end program...");
        Console.ReadKey();


    }
}

}

Capturing standard output from console app

Here's code that redirects output from my Proofreading Tracker console app:

using System;
using System.Diagnostics;

sealed class TestRedirStdOutput
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.Arguments = "titles";
        p.StartInfo.FileName = "prt.exe";
        p.Start();

        // To avoid deadlocks, always read the output stream first and then wait.
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        Console.WriteLine(" Captured this output:\n");
        Console.WriteLine(output + "\n");
        Console.WriteLine(" Press any key to exit...");
        Console.ReadLine();
    }
}

Prevent Multiple Instances of .NET App

Sometimes there are good reasons not to allow any copies of your app to be executing alongside one another. We only want a single instance of the app running on any given machine.

The links below connect to downloadable examples of implementing a mutex lock in .NET applications.

Download the Console app example.

Below is the complete code from Program.cs of a WinForms C# app that shows usage of a mutex to prevent multiple instances:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace ProofreadingTracker
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            string mutexName = "Local\\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            using (Mutex mutex = new Mutex(false, mutexName))
            {
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show("There is an instance of this application already running!", "Proofreading Tracker");
                    return;
                }
                else
                {
                    GC.Collect();
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                }
            }
        }
    }
}