Friday 31 January 2014

c# async TCP/IP server & multiple clients

    2 computers cross-over cable connection 

start client 1

get server @ from server screen

client 1 connect to server

client 1 send to server

client 1 get reply from server

while client 1 still alive, client 2 talk to server

client 2 gets no reply

while client 1,2 online, client 3 connects to server


client 4 joins with other clients

client 4 doesn't get reply immediately

client 1 disconnected

server reply to client 2

client 2 finishes

client 3 receive from server and leaves

client 4 gets message

client 4 quit

server show local addresses

server receive call from 4 client, handle them 1 by 1.

client 1 gone, server has time with 2nd client

client 2 gone, server tackle with client 3

most clients are gone, deal with the last one

everybody left, waiting for new client

computers connect via router by cable or wifi 


start client

ping server

no data lose

start server

server call back

communication successful, next client


//tcpserver async
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.Net;
using System.Net.Sockets;

namespace server_async
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            richTextBox1.AppendText("local server address\n");

            foreach (IPAddress x in ipHostInfo.AddressList)
            {
                richTextBox1.AppendText(x.ToString()+"\n");
            }

            server = new Socket(AddressFamily.InterNetwork,
                   SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            server.Bind(iep);
            server.Listen(5);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);
        }

        public delegate void callrichtext(String ss);
        public callrichtext myDelegate;

        public void richtextappend(String s)
        {
            richTextBox1.AppendText(s);
        }

        public delegate void callrichtext1(String ss);
        public callrichtext1 myDelegate1;

        public void richtextappend1(String s)
        {
            richTextBox2.AppendText(s);
        }

        private Socket server, oldclient;
        private byte[] data = new byte[1024];
        private int size = 1024;

        private void AcceptConn(IAsyncResult iar)
        {
            Socket oldserver = (Socket)iar.AsyncState;
            oldclient = oldserver.EndAccept(iar);
            richTextBox1.Invoke(this.myDelegate, new Object[] { "Connected to: " + oldclient.RemoteEndPoint.ToString() + "\n" });
            string stringData = "Welcome to my server";
            byte[] message1 = Encoding.ASCII.GetBytes(stringData);
            oldclient.BeginSend(message1, 0, message1.Length, SocketFlags.None,
                        new AsyncCallback(SendData), oldclient);
        }

        private void SendData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            client.BeginReceive(data, 0, size, SocketFlags.None,
                        new AsyncCallback(ReceiveData), client);
        }

        private void ReceiveData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int recv = client.EndReceive(iar);
            //MessageBox.Show(recv.ToString());
         
            if (recv == 0)
            {
                client.Close();
                richTextBox1.Invoke(this.myDelegate, new Object[]{ "Waiting for client..."+"\n"});
                server.BeginAccept(new AsyncCallback(AcceptConn), server);
                return;
            }
            string receivedData = Encoding.ASCII.GetString(data, 0, recv);
            richTextBox2.Invoke(this.myDelegate1, new Object[] {receivedData + "\n"});
            byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
            client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
                         new AsyncCallback(SendData), client);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.myDelegate = new callrichtext(richtextappend);
            this.myDelegate1 = new callrichtext1(richtextappend1);
        }

    }
}

----------------------------------------------------------------------------
//tcpclient async
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.Net;
using System.Net.Sockets;

namespace tcpclient_async
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress x in ipHostInfo.AddressList)
            {
                comboBox1.Items.Add (x.ToString());
            }
        }

        public delegate void callrichtext(String ss);
        public callrichtext myDelegate;

        public void richtextappend(String s)
        {
            richTextBox1.AppendText(s);
        }

        public delegate void callrichtext1(String ss);
        public callrichtext1 myDelegate1;

        public void richtextappend1(String s)
        {
            richTextBox2.AppendText(s);
        }

        public delegate void callrichtext2(String ss);
        public callrichtext2 myDelegate2;

        public void richtextappend2(String s)
        {
            richTextBox3.AppendText(s);
        }

        public delegate void buttonenable();
        public buttonenable myDelegate3;

        public void button()
        {
            button2.Enabled=true;
        }

        private Socket client;
        private byte[] data = new byte[1024];
        private int size = 1024;

        private void Form1_Load(object sender, EventArgs e)
        {
            this.myDelegate = new callrichtext(richtextappend);
            this.myDelegate1 = new callrichtext1(richtextappend1);
            this.myDelegate2 = new callrichtext2(richtextappend2);
            this.myDelegate3 = new buttonenable(button);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox3.AppendText( "Connecting... \n");
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 9050);
            newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] message = Encoding.ASCII.GetBytes(richTextBox2.Text);
            richTextBox2.Clear();
            client.BeginSend(message, 0, message.Length, SocketFlags.None,
                         new AsyncCallback(SendData), client);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            client.Close();
            richTextBox3.AppendText ("Disconnected \n");
        }

        private void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                richTextBox3.Invoke(this.myDelegate2, new Object[] { "Connected to: " + client.RemoteEndPoint.ToString() +"\n"});
                client.BeginReceive(data, 0, size, SocketFlags.None,
                              new AsyncCallback(ReceiveData), client);
                button2.Invoke(this.myDelegate3, new Object[] { });
            }
            catch (SocketException)
            {
                richTextBox3.Invoke(this.myDelegate2, new Object[] { "Error connecting \n"});
            }
        }

        private void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            richTextBox1.Invoke(this.myDelegate, new Object[]{stringData+"\n"});
        }

        private void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int sent = remote.EndSend(iar);
            remote.BeginReceive(data, 0, size, SocketFlags.None,
                          new AsyncCallback(ReceiveData), remote);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = comboBox1.SelectedItem.ToString();
        }

    }
}


Async Tcp background:
 http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm

reference:
http://forums.codeguru.com/showthread.php?509248-How-to-run-a-very-long-SQL-statement
http://msdn.microsoft.com/en-us/library/5w7b7x5f(v=vs.110).aspx
http://www.java2s.com/Code/CSharp/Network/AsyncTcpServer.htm
http://www.java2s.com/Code/CSharp/Network/AsyncTcpClient.htm

Thursday 23 January 2014

c# hyperterminal usb serial communication interrupt








video:
https://www.youtube.com/watch?v=fZd2PfuhQ7Y
https://www.youtube.com/watch?v=_wovNBQpu2o

//form1.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.Ports;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
         
            mySerialPort.BaudRate = Class1.baudrate;

            switch (Class1.parity)
            {
                case "Even":
                    mySerialPort.Parity = Parity.Even;
                    break;
                case "Odd":
                    mySerialPort.Parity = Parity.Odd;
                    break;
                case "None":
                    mySerialPort.Parity = Parity.None;
                    break;
                default:
                    break;
            }
         
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = Class1.databits;
            mySerialPort.Handshake = Handshake.None;

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

            richTextBox1.AppendText("open\n");

        }

        private SerialPort mySerialPort = new SerialPort(Class1.comport);

        public delegate void callrichtext(String ss);
        public callrichtext myDelegate;

        public void richtextappend(String s)
        {
            richTextBox2.AppendText(s);
        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();

            richTextBox1.Invoke(this.myDelegate, new Object[] { indata });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.myDelegate = new callrichtext(richtextappend);
        }

        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            mySerialPort.Write(Convert.ToString(e.KeyChar));
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("new connection?", "inquiry", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Application.Restart();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mySerialPort.Close();
        }

     
    }
}

----------------------------------------------------------------------------------------------------------
//form2.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.Ports;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

            button1.Enabled = false;

            foreach (string s in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(s);
            }
        }

        private bool[] ok = { false, false, false,false};

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Class1.comport = comboBox1.SelectedItem.ToString();
            ok[0] = true;
            if (okenable(ok)) { button1.Enabled = true; }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Class1.baudrate = Convert.ToInt32(comboBox2.SelectedItem);
            ok[1] = true;
            if (okenable(ok)) { button1.Enabled = true; }
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            Class1.databits = Convert.ToInt32(comboBox3.SelectedItem);
            ok[2] = true;
            if (okenable(ok)) { button1.Enabled = true; }
        }

        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {
            Class1.parity = comboBox4.SelectedItem.ToString();
            ok[3] = true;
            if (okenable(ok)) { button1.Enabled = true; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form1 hyperterm = new Form1();
            hyperterm.Show();
        }

        private bool okenable(bool[] ok)
        {
            bool x = true;
            foreach (bool b in ok)
            {
                if (b == false) { x = false; }
            }

            return x;
        }
    }
}

----------------------------------------------------------------------------------------------------
//class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class Class1
    {
        private static Form2 x = new Form2();
        public static Form2 mainForm
        {
            set { x = value; }
            get { return x; }
        }

        private static string y;
        public static string comport
        {
            set { y = value; }
            get { return y; }
        }

        private static int z;
        public static int baudrate
        {
            set { z = value; }
            get { return z; }
        }

        private static int u;
        public static int databits
        {
            set { u = value; }
            get { return u; }
        }

        private static string v;
        public static string parity
        {
            set { v = value; }
            get { return v; }
        }
    }
}

-------------------------------------------------------------------------------------------------------
//program.cs

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

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Class1.mainForm);
        }
    }
}

reference:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/0388ec40-47f1-44f8-a25d-d0d5e7ddf2d2/usb-communication-from-c?forum=csharpgeneral

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx

Monday 13 January 2014

98 jeep grand cherokee wiring diagram



http://www.autozone.com/autozone/repairinfo/repairguide/repairGuideContent.jsp?pageId=0900c152800a9de9

http://cr4.globalspec.com/thread/47663/Jeep-Grand-Cherokee-1998-Automatic-Shutdown-Device



c# eventlog calendar defaultbutton formclose mdicontainer



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.Net;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Form2 frm = new Form2();
            frm.MdiParent = this;
            frm.Show();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           /* string s = "";
            IPAddress[] addresslist = Dns.GetHostEntry(Dns.GetHostName()).AddressList;

            for (int i = 0; i < addresslist.Length; i++)
            {
                s += addresslist[i].ToString() + "\n";
            }

            richTextBox1.Text = s;*/

            /* if (SystemInformation.Network)
            {
                MessageBox.Show("connected");
            }
            else
            {
                MessageBox.Show("disconnected");
            }*/

           /* this.AcceptButton = button1;
            this.CancelButton = button1;*/


        }

        private void button1_Click(object sender, EventArgs e)
        {
          /*  this.eventLog1.Log = "Application"; //System, Security, 
            EventLogEntryCollection collection = eventLog1.Entries;
            int count = collection.Count;
            string info = "#" + count.ToString() + " events";
            foreach (EventLogEntry entry in collection)
            {
                info += "\n type: " + entry.EntryType.ToString();
                info += "\n date: " + entry.TimeGenerated.ToLongDateString();
                info += "\n time: " + entry.TimeGenerated.ToLongTimeString();
                info += "\n source: " + entry.Source;
                info += "\n event: " + entry.InstanceId.ToString();
                info += "\n user: " + entry.UserName;
                info += "\n computer: " + entry.MachineName;
            }
            this.richTextBox1.Text = info;*/

          /* if (!EventLog.SourceExists(textBox1.Text))
            {
                EventLog.CreateEventSource(textBox3.Text, textBox1.Text);
            }
            
            EventLog log = new EventLog();
            log.WriteEntry(textBox2.Text);*/

            myear = monthCalendar1.SelectionRange.Start.Year;
            mmonth = monthCalendar1.SelectionRange.Start.Month;
            mday = monthCalendar1.SelectionRange.Start.Day;           

            SystemTime t = new SystemTime();

            t.wYear = (ushort)myear;
            t.wMonth = (ushort)mmonth;

            textBox1.Text = t.wYear.ToString();
            textBox2.Text = t.wMonth.ToString();

            SetSystemTime(ref t);
          
        }

        private int myear, mday, mmonth;

        [DllImport("Kernel32.dll")]
        public static extern bool SetSystemTime(ref SystemTime sysTime);

        [DllImport("Kernel32.dll")]
        public static extern void GetSystemTime(ref SystemTime sysTime);

        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);

        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SystemTime sysTime);


        public struct SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMiliseconds;
        }  

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
           /* myear = e.Start.Year;
            mmonth = e.Start.Month;
            mday = e.Start.Day; */
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("close?", "inquiry", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}


c# listbox combobox



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.Collections;
using System.Net;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Control == true) && (e.KeyCode == Keys.A ))
            {
                MessageBox.Show("ctrl+A");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            string[] logicdrives = System.IO.Directory.GetLogicalDrives();
            for (int i = 0; i < logicdrives.Length; i++)
            {
                comboBox1.Items.Add(logicdrives[i]);
            }


            listView1.Columns.Add("environment", 150, HorizontalAlignment.Left);
            listView1.Columns.Add("value", 150, HorizontalAlignment.Left);
            listView1.Columns.Add("value2", 150, HorizontalAlignment.Left);

            ListViewItem myitem;
            foreach (DictionaryEntry dentry in Environment.GetEnvironmentVariables())
            {
                myitem = new ListViewItem(dentry.Key.ToString(), 0);
                myitem.SubItems.Add(dentry.Value.ToString());
                myitem.SubItems.Add("aaa");
                listView1.Items.Add(myitem);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.IO.DriveInfo[] drive = System.IO.DriveInfo.GetDrives();

            switch(comboBox1.SelectedItem.ToString())
            {
                case @"C:\":
                    label1.Text = drive[0].TotalSize/1024/1024/1024 + "G";
                    label2.Text = drive[0].TotalFreeSpace / 1024 / 1024 / 1024 + "G";
                    label3.Text = (drive[0].TotalSize - drive[0].TotalFreeSpace) / 1024 / 1024 / 1024 + "G";
                    break;

                case @"D:\":
                    label1.Text = drive[1].TotalSize / 1024 / 1024 / 1024 + "G";
                    label2.Text = drive[1].TotalFreeSpace / 1024 / 1024 / 1024 + "G";
                    label3.Text = (drive[1].TotalSize - drive[1].TotalFreeSpace) / 1024 / 1024 / 1024 + "G";
                    break;

                default:
                    break;
            }

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar))
            {
                MessageBox.Show("only number");
                e.Handled = true;
            }
        }
    }
}


c# mouse event


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.Drawing.Drawing2D;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Start();
        }

        private Point[] a = new Point[0];
        private Point c=new Point();
        private int num = 0, picnum =0;
        private GraphicsPath myPath;

        private void Form1_Load(object sender, EventArgs e)
        {        
            this.Cursor = Cursors.Hand;
        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                label1.Text = "left";
            }

            if (e.Button == MouseButtons.Right)
            {
                label1.Text = "right";
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;

            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                for (int i = 0; i < files.Length; i++)
                {
                    listBox1.Items.Add(files[i]);
                }
            }
        }

        private void Form1_DoubleClick(object sender, EventArgs e)
        {
            SendKeys.Send("{Tab}");
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
         
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point[] b = new Point[num];
                b = a;
                num++;
                Array.Resize(ref a, num);

                for (int i = 0; i < num - 1; i++)
                {
                    a[i] = b[i];
                }
                a[num - 1] = new Point(e.X, e.Y);
            }

            if (e.Button == MouseButtons.Right)
            {
                num = 0;
                Array.Resize(ref a, 0);
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            c = new Point(e.X, e.Y);
            this.Refresh();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Pen blackpen = new Pen(Color.Black, 2);
            myPath = new GraphicsPath();

            if (num>0)
            {
                for (int i = 0; i < num-1; i++)
                {
                    myPath.AddLine(a[i],a[i+1]);
                }
                e.Graphics.DrawPath(blackpen, myPath);
                e.Graphics.DrawLine(blackpen, a[num-1], c);
            }
                                 
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Rectangle bounds = this.Bounds;
            Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
            Graphics g = Graphics.FromImage(bitmap);

            g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            bitmap.Save("test" + picnum + ".jpg");
            picnum++;
            this.Refresh();
        }
    }
}

c# opacity clipboard buttonfocus mutex




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.Collections;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Start();
            timer3.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Opacity = 0;
            count = false;
            Random rdn = new Random();
            int i = rdn.Next(imageList1.Images.Count);
            this.BackgroundImage = imageList1.Images[i];
            this.BackgroundImageLayout = ImageLayout.Stretch;
            timer1.Stop();
            timer2.Start();

        }

        private bool op = true, count = false;
        private int picnum = 0;

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (this.Opacity == 1) { op = false; }
            if (this.Opacity == 0) { op = true; if (count == false) { count = true; } else { count = false; } }

            if (count == false) { timer2.Stop(); timer1.Start(); }

            if (op == false) { this.Opacity -= 0.1; }
            else { this.Opacity += 0.1; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                richTextBox1.Text = Clipboard.GetText();
                string[] strArr = Clipboard.GetText().Split(' ');

                foreach (string abc in strArr)
                {
                    listBox1.Items.Add(abc);
                }
            }
        }

        private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                button1.Focus();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            /* string RunningProcess = Process.GetCurrentProcess().ProcessName;
             Process[] processes = Process.GetProcessesByName(RunningProcess);
             if (processes.Length > 1)
             {
                 MessageBox.Show("Application is already running", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 Application.Exit();
                 Application.ExitThread();
             }*/

            bool exist;
            System.Threading.Mutex mx = new System.Threading.Mutex(true, "only once", out exist);
            if (exist)
            {
                mx.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("one at a time!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            Rectangle bounds = this.Bounds;
            Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
            Graphics g = Graphics.FromImage(bitmap);

            g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            bitmap.Save("test" + picnum + ".jpg");
            picnum++;
            this.Refresh();
        }
     
    }
 
}