Thursday, February 20, 2014

How to communicate between forms?

Form2.cs:

        private Form1 mainForm = null;

        public Form2(Form callingForm) //put the calling form as arg
        {
                InitializeComponent();
                mainForm = callingForm as Form1;
        }
       

Form1.cs

        private Form2 subForm = null;

        subForm = new Form2(this);
        subForm.show();

Wednesday, February 19, 2014

How to use threading with buffer (with correct way of terminating the thread)?

using System.Threading;

namespace Form1
{
    public partial class Form1: Form
    {

        //Threading
        private Thread processorThread = null;
        private readonly object _locker = new object();
        private volatile bool _shouldStop = false; //To exit thread cleanly
        private Queue<int> buffer = new Queue<int>();


        public Form1(Form callingForm, int formNum)
        {
              processorThread= new Thread(processNumber);
              processorThread.IsBackground = true; //Thread will terminate automatically when program close
              processorThread.Start();
         }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _shouldStop = true;
            processorThread.Interrupt();
            processorThread.Join(3000);
         }

        private void processNumber()
        {
            int myNumber;

            while (!_shouldStop)
            {
                try
                {
                    lock (_locker)
                    {
                        if (buffer.Count == 0)
                            Monitor.Wait(_locker); //Releases the lock on an object and blocks the current thread until it reacquires the lock.
                    }
                    lock (_locker)
                    {
                        myNumber= buffer.Dequeue();
                    }

                    tsDictionary = displayNumber(myNumber);
                }
                catch (Exception err)
                {
                    //MessageBox.Show(this, "processNumber(): " + err.Message);
                }
            }
        }

        private void number_Update(object sender, EventArgs e) //an imaginary event that send a random number on random time
        {          
            try
            {
                if (e != null)
                {
                    lock (_locker)
                    {
                        buffer.Enqueue(e.number);
                        Monitor.Pulse(_locker); //Notifies a thread in the waiting queue of a change in the locked object's state - i.e. "wake" the waiting thread
                    }
                }
            }
            catch (Exception err)
            {
            }

        }

        void displayNumber(int number)
        {
            if (label1.InvokeRequired)
            {
                MethodInvoker invoker = () => displayNumber(number);
                label1.Invoke(invoker);
            }
            else
                label1.Text += " " + number.ToString();
         }
     }
}
     

Tuesday, February 18, 2014

How to use custom cursor from resource?

using System.Runtime.InteropServices;
using System.IO;

namespace Form1
{
    public partial class Form1: Form
    {

        private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(Form1.Properties.Resources.yl_cur);
        private Cursor yellowCursor = LoadCursorFromResource(cursorMemoryStream);
        this.Cursor = yellowCursor;


        [DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern IntPtr LoadCursorFromFile(String str);

        public static Cursor LoadCursorFromResource(System.IO.MemoryStream cursorMemoryStream)
        {      

             using (var fileStream = File.Create(@".\tempCursor.cur"))
             {
                 cursorMemoryStream.CopyTo(fileStream);
             }

             Cursor result = new Cursor(LoadCursorFromFile(@".\tempCursor.cur"));
             File.Delete(@".\tempCursor.cur");

             return result;
        }

How to disable selection in DataGridView?

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            dataGridView1.CurrentCell.Selected = false;
        }

Thursday, February 6, 2014

How to disable close button on winForm?

using System.Runtime.InteropServices; //For "DllImportAttribute"

namespace Form1
{
    public partial class Form1 : Form
    {

        public Form1()
        {  
            InitializeComponent();
            CloseButton.EnableDisable(this, false);
}

     class CloseButton
        {
            private const int SC_CLOSE = 0xF060;
            private const int MF_GRAYED = 0x1;

            [DllImport("user32.dll")]
            private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

            [DllImport("user32.dll")]
            private static extern int EnableMenuItem(IntPtr hMenu, int wIDEnableItem, int wEnable);

            public static void EnableDisable(Form form,bool isEnable)
            {
                EnableMenuItem(GetSystemMenu(form.Handle, isEnable), SC_CLOSE,  MF_GRAYED);
            }

        }
}

How to do Inter-Process Communication through Named Pipes?

Server.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

//Added
using System.IO.Pipes;
using System.IO;
using System.Threading;
using System.Security.Principal;
using server;
//using PipeServer;


namespace server
{
    /// <summary>
    /// PipeServer creates a listener thread and waits for messages from clients.
    /// Received messages are displayed in Textbox
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            tbox.Text = "";
            Pipeserver.pipeName = "testpipe";
            Pipeserver.owner = this;
            //Pipeserver.ownerInvoker = new Invoker(this);
            ThreadStart pipeThread = new ThreadStart(Pipeserver.createPipeServer);
            Thread listenerThread = new Thread(pipeThread);
            listenerThread.SetApartmentState(ApartmentState.STA);
            listenerThread.IsBackground = true;
            listenerThread.Start();
        }

        public void setTextbox(string text)
        {
            if (tbox.InvokeRequired)
            {
                MethodInvoker invoker = () => setTextbox(text);
                tbox.Invoke(invoker);
            }
            else
            {
                tbox.Text = text;
            }
        }
    }




    public class Pipeserver
    {
        public static Form1 owner;
        //public static Invoker ownerInvoker;
        public static string pipeName;
        private static NamedPipeServerStream pipeServer;
        private static readonly int BufferSize = 256;

        //private static void SetTextbox(String text)
        //{
        //    owner.tbox.Text = String.Concat(owner.tbox.Text, text);
        //    if (owner.tbox.ExtentHeight > owner.tbox.ViewportHeight)
        //    {
        //        owner.tbox.ScrollToEnd();
        //    }
        //}

        public static void createPipeServer()
        {
            Decoder decoder = Encoding.Default.GetDecoder();
            Byte[] bytes = new Byte[BufferSize];
            char[] chars = new char[BufferSize];
            int numBytes = 0;
            StringBuilder msg = new StringBuilder();
            //ownerInvoker.sDel = SetTextbox;

            try
            {
                pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
                                                PipeTransmissionMode.Message,
                                                PipeOptions.Asynchronous);
                while (true)
                {
                    pipeServer.WaitForConnection();

                    do
                    {
                        msg.Length = 0;
                        do
                        {
                            numBytes = pipeServer.Read(bytes, 0, BufferSize);
                            if (numBytes > 0)
                            {
                                int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                                decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                                msg.Append(chars, 0, numChars);
                            }
                        } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                        decoder.Reset();
                        if (numBytes > 0)
                        {
                            owner.setTextbox(msg.ToString());//ownerInvoker.Invoke(msg.ToString());
                        }
                    } while (numBytes != 0);
                    pipeServer.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}




Client.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
using System.Security.Principal;

namespace Client
{
    public partial class Form1 : Form
    {
        public NamedPipeClientStream PipeStream;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

              using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe",
                                                          PipeDirection.Out,
                                                             PipeOptions.Asynchronous))
              {
                tbStatus.Text = "Attempting to connect to pipe...";
                try
                {
                  pipeClient.Connect(2000);
                }
                catch
                {
                  MessageBox.Show("The Pipe server must be started in order to send data to it.");
                  return;
                }
                tbStatus.Text = "Connected to pipe.";
                using (StreamWriter sw = new StreamWriter(pipeClient))
                {
                  sw.WriteLine(textBox1.Text);
                }
              }
              tbStatus.Text = "";

        }
    }
}


Wednesday, February 5, 2014

How to make font bold and italics?

Font a = new Font("Arial", 9, FontStyle.Bold | FontStyle.Italic);

How to read write XML files?

using System.Xml;

       //##################### READ / WRITE #####################
        private void ReadSettingsXML()
        {
            if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
                return;

            XmlReader reader = XmlReader.Create(@".\DatFiles\Settings.xml");
            try
            {
                while (reader.Read())
                {
                    // Only detect start elements.
                    if (reader.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (reader.Name)
                        {
                            case "locX":
                                if (reader.Read())
                                {
                                    locX = Convert.ToInt32(reader.Value);
                                }
                                break;

                            case "locY":
                                if (reader.Read())
                                {
                                    locY = Convert.ToInt32(reader.Value);
                                }
                                break;    
                        }
                    }
                }
                reader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "ReadSettingsXML() " + e.Message, "Exception");
            }
        }

        //************* WriteSettingsXML() *************
        private void WriteSettingsXML()
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.Encoding = System.Text.Encoding.UTF8;

            if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
            {
                System.IO.Directory.CreateDirectory(@".\DatFiles\");
            }

            XmlWriter xmlw = XmlWriter.Create(@".\DatFiles\Settings.xml", settings);

            xmlw.WriteStartDocument();
            xmlw.WriteStartElement("settings");
           
            xmlw.WriteStartElement("locX");
            xmlw.WriteValue(locX);
            xmlw.WriteEndElement();
           
            xmlw.WriteStartElement("locY");
            xmlw.WriteValue(locY);
            xmlw.WriteEndElement();

            xmlw.WriteEndElement(); //Settings
            xmlw.WriteEndDocument();
            xmlw.Close();
        }
     

How to make textbox a password text box?

textBox1.PasswordChar = '*';

How to encrypt and decrypt files?

using System.Security.Cryptography;       

namespace Form1
{
    public partial class Form1 : Form
    {
        static readonly string PasswordHash = "abcdef";
        static readonly string SaltKey = "S@LT&KEY";
        static readonly string VIKey = "@afag214@#%afa";

      //************* ReadProtectedInfo() *************
        private bool ReadProtectedInfo()
        {
            try
            {
                if (!System.IO.File.Exists(@openFilePath))
                {
                    return false;
                }

                char[] delimiterChars = { ' ', '\n', '\r' };

                infoString = Decrypt(System.IO.File.ReadAllText(@openFilePath));
                info = infoString.Split(delimiterChars);

                return true;

            }
            catch (Exception e)
            {
                MessageBox.Show(this, "ReadProtectedInfo() " + e.Message, "Exception");
                return false;
            }
        }
        //************* WriteProtectedInfo() *************
        private void WriteProtectedInfo()
        {
            if (!System.IO.File.Exists(@saveFilePath))
            {
                //System.IO.Directory.CreateDirectory(@".\DatFiles\");
                var myFile = System.IO.File.Create(@saveFilePath);
                myFile.Close();
            }

            string info = Encrypt(richTextBox1.Text);

            System.IO.File.WriteAllText(@saveFilePath, info, Encoding.UTF8);
        }


        // ################### ENCRYPTION ###################
        public static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string Decrypt(string encryptedText)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }

How to draw rounded rectangles / borders?

using System.Drawing.Drawing2D;     

 public void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius, bool fill, System.Drawing.Brush brush)
        {
            try
            {
                GraphicsPath gp = new GraphicsPath();
                gp.AddLine(X + radius, Y, X + width - (radius * 2), Y);
                gp.AddArc(X + width - (radius * 2), Y, radius * 2, radius * 2, 270, 90);
                gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius * 2));
                gp.AddArc(X + width - (radius * 2), Y + height - (radius * 2), radius * 2, radius * 2, 0, 90);
                gp.AddLine(X + width - (radius * 2), Y + height, X + radius, Y + height);
                gp.AddArc(X, Y + height - (radius * 2), radius * 2, radius * 2, 90, 90);
                gp.AddLine(X, Y + height - (radius * 2), X, Y + radius);
                gp.AddArc(X, Y, radius * 2, radius * 2, 180, 90);
                gp.CloseFigure();
                if (fill)
                    g.FillPath(brush, gp);
                g.DrawPath(p, gp);
                gp.Dispose();
            }
            catch (Exception ee)
            {
                MessageBox.Show(this, "DrawRoundRect" + ee.Message, "Exception");
            }
        }

        private void backPanel_Paint(object sender, PaintEventArgs e)
        {
            Graphics v = e.Graphics;
            v.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Pen pathPen = new Pen(Color.Black, 1);
            DrawRoundRect(v, pathPen, backPanel.Left - 2, backPanel.Top - 2, backPanel.Width - 2, backPanel.Height - 2, 6, false, null);
            base.OnPaint(e);
        }

How to have custom font?

using System.Drawing;
using System.Runtime.InteropServices;

namespace Form1
{
    public partial class Form1 : Form
    {
        //Add Font
        [DllImport("gdi32.dll")]
        private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
          IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

        FontFamily ff;
        Font font;
    }

        private void Form1_Load(object sender, EventArgs e)
        {
              LoadFont();
              this.Font = new Font(ff, 15f, FontStyle.Regular);
        }

        private void LoadFont()
        {
            try
            {
                byte[] fontArray = GPnL.Properties.Resources.helveticaneuewebfont;
                int dataLength = GPnL.Properties.Resources.helveticaneuewebfont.Length;

                IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);

                Marshal.Copy(fontArray, 0, ptrData, dataLength);

                uint cFonts = 0;

                AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);

                PrivateFontCollection pfc = new PrivateFontCollection();

                pfc.AddMemoryFont(ptrData, dataLength);

                Marshal.FreeCoTaskMem(ptrData);
                ff = pfc.Families[0];

                font = new Font(ff, 15f, FontStyle.Regular);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "loadFont" + e.Message, "Exception");
            }
        }

How create rounded corner form?

namespace Form1
{
    public partial class Form1 : Form
    {
        //Cut Border
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
        (
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
         );
    }
        public Form1()
        {
                InitializeComponent();
                Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
        private void Form1_Resize(object sender, EventArgs e)
        {
            Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 15, 15));
        }

How to make font resize automatically based on label size?

        private void Form1_Resize(object sender, EventArgs e)
        {
            pixels = Math.Min(label1.Height, label1.Width/2.8);
            float fontSize = (float)(pixels * 0.8 * 72.0 / 96.0); //this is the magic
            this.Font = new Font("Arial", fontSize, FontStyle.Bold);
        }


How to move borderless forms?

using System.Runtime.InteropServices; //For "DllImportAttribute"

namespace Form1
{
    public partial class Form1: Form
    {
        //To move 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();

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

How to resize borderless forms?

Change form's padding to 3,3,3,3 to leave a space for the mouse to click and drag

//resize form
        protected override void WndProc(ref Message m)
        {
            const UInt32 WM_NCHITTEST = 0x0084;
            const UInt32 WM_MOUSEMOVE = 0x0200;

            const UInt32 HTLEFT = 10;
            const UInt32 HTRIGHT = 11;
            const UInt32 HTBOTTOMRIGHT = 17;
            const UInt32 HTBOTTOM = 15;
            const UInt32 HTBOTTOMLEFT = 16;
            const UInt32 HTTOP = 12;
            const UInt32 HTTOPLEFT = 13;
            const UInt32 HTTOPRIGHT = 14;

            const int RESIZE_HANDLE_SIZE = 10;
            bool handled = false;
            if (m.Msg == WM_NCHITTEST || m.Msg == WM_MOUSEMOVE)
            {
                Size formSize = this.Size;
                Point screenPoint = new Point(m.LParam.ToInt32());
                Point clientPoint = this.PointToClient(screenPoint);

                Dictionary<UInt32, Rectangle> boxes = new Dictionary<UInt32, Rectangle>() {
            {HTBOTTOMLEFT, new Rectangle(0, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
            {HTBOTTOM, new Rectangle(RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
            {HTBOTTOMRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
            {HTRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE)},
            {HTTOPRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
            {HTTOP, new Rectangle(RESIZE_HANDLE_SIZE, 0, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
            {HTTOPLEFT, new Rectangle(0, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
            {HTLEFT, new Rectangle(0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE) }
        };

                foreach (KeyValuePair<UInt32, Rectangle> hitBox in boxes)
                {
                    if (hitBox.Value.Contains(clientPoint))
                    {
                        m.Result = (IntPtr)hitBox.Key;
                        handled = true;
                        break;
                    }
                }
            }

            if (!handled)
                base.WndProc(ref m);
        }