Tuesday 26 November 2013

Run a program automatically when Windows starts short cut display 'Windows startup' and add 'system tray'


 







using IWshRuntimeLibrary;
using Microsoft.Win32;
using System.IO;


namespace Sample
{
        public partial class Form1 : Form
        {
                    RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows \\CurrentVersion\\Run", true) // check windows is run     
                    private NotifyIcon tryIcon; //add icon in 'System Tray'
                   private ContextMenu trayMenu;  // create menu
            
               public Form1()
             {
                      // if windows is run my app (setup1) is run
                      reg.SetValue("MyApp", Application.ExecutablePath);
                      MessageBox.Show("Test");
           

                       //create Menu Item
                       trayMenu = new ContextMenu ();

            //Menu Item (Show, Hide, Exit) ==> menu Function (OnShow, OnHide, OnExit) in #region System Tray Menu
            trayMenu.MenuItems.Add("Show", OnShow);
            trayMenu.MenuItems.Add("Hide", OnHide);
            trayMenu.MenuItems.Add("Exit", OnExit);

            // Display icon in "System Tray" (refer image first) 

            tryIcon = new NotifyIcon(); // set Systen tray icon
            tryIcon.Text = "Setup1"; // set system tray text
            // how to add resources  -> click 'Properties' -> open the 'Resources.resx' -> change to string to icon  -> click 'Add Resource' - select 'Add Existing file' and select icon
            tryIcon.Icon = Properties.Resources.ftprush_install; // add icon in 'System Tray'
           tryIcon.ContextMenu = trayMenu; // add menu at "System try"
            tryIcon.Visible = true; // Icon visible true
           
            InitializeComponent();
        }
        void CreateStartupShortcut()  // Display "Windows Startup" (refer image 2)
        {           
            string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            WshShell shell = new WshShell();
            string shortcutAddress = startupFolder + @"\MYApp.lnk";
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
            shortcut.Description = "A startup shortcut. If you delete this shortcut from your computer,   LaunchOnStartup.exe will not launch on Windows Startup"; // set the description of the shortcut
            shortcut.WorkingDirectory = Application.StartupPath; /* working directory */
            shortcut.TargetPath = Application.ExecutablePath; /* path of the executable */
            // optionally, you can set the arguments in shortcut.Arguments
            // For example, shortcut.Arguments = "/a 1";

            shortcut.Save();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Opacity = 0; // form not display (this is hide)
            this.ShowInTaskbar = false; // display hide in Task bar
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; // in       Design mode:
        }

        #region System Tray Menu
        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OnShow(object sender, EventArgs e)
        {
            this.Opacity =1;  // form  display (this is show)
            this.ShowInTaskbar = true // display  in Task bar           
        }

        private void OnHide(object sender, EventArgs e)
        {
            this.Opacity = 0;  // form not display (this is hide)
            this.ShowInTaskbar = false// display hide in Task bar
        }
        #endregion System Tray Menu

         }
}

Download  Sample Coding (LaunchOnStartUp.rar)

Download  Interop.IWshRuntimeLibrary.dll

Wednesday 20 November 2013

How to get Listview subitems index

if (listview1.SelectedItems.Count > 0)
{
                int icolcount = 0; string  sID = "";
                foreach (ColumnHeader header in listview1.Columns)
                {  
                    if (header.Text.ToLower().Trim() == "id")
                    {
                        sID= listview1.SelectedItems[0].SubItems[icolcount].Text;
                        break;
                    }
                    icolcount ++;
                }
}

Saturday 16 November 2013

How to change Listview subitem back color

How to change the backcolor of a listview subitem using its own value

ListViewItem newlist= new ListViewItem( "Item 1");
newlist.SubItems.Add( "Color" );
newlist.SubItems[1].BackColor = Color.FromArgb( -16711936 );
newlist.UseItemStyleForSubItems = false;

listView1.Items.Add( newlist);

A free, cross-platform browser-based IDE (ASP.NET work online)

CodeRun Studio is a free service

CodeRun Studio is a cross-platform Integrated Development Environment (IDE), designed for the cloud. It enables you to easily develop, debug and deploy web applications using your browser.
CodeRun Studio can be used instead or alongside your existing desktop IDE. You can upload existing code in order to test it in the cloud or for sharing with your peers.

Friday 8 November 2013

Avoid confirmation box in MsiExec uninstall



MsiExec.exe /I{A52EEC0E-D0B7-4345-A0FF-574804C7B78A} /passive

{A52EEC0E-D0B7-4345-A0FF-574804C7B78A} --> is Product Code
 
If you want to completely hide the UI, use the /quiet (நீங்கள் முற்றிலும் UI மறைக்க விரும்பினால்)

switch instead of /passive.


Example C#

            Process p = new Process();
            p.StartInfo.FileName = "msiexec.exe";
            p.StartInfo.Arguments = "/x {A52EEC0E-D0B7-4345-A0FF-574804C7B78A} /passive";
            p.Start();

OR

            Process p = new Process();
            p.StartInfo.FileName = "msiexec.exe";
            p.StartInfo.Arguments = "/x {A52EEC0E-D0B7-4345-A0FF-574804C7B78A} /quiet";
            p.Start();

             Process p = new Process();
            p.StartInfo.FileName = "msiexec.exe";
            p.StartInfo.Arguments = "/qn /x {A52EEC0E-D0B7-4345-A0FF-574804C7B78A}";
            p.Start();

Saturday 14 September 2013

Color to RGB and hex Value

HexConverter
 
DialogResult result = colorDialog1.ShowDialog();
if (result == DialogResult.OK)
{
    Color c=colorDialog1.Color;
    string HexConverter= "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

RGBConverter

DialogResult result = colorDialog1.ShowDialog();
if (result == DialogResult.OK)
{
    Color c=colorDialog1.Color;
    string HexConverter= "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Tuesday 10 September 2013

C# array null/empty string values

String[] URL= {"1","2","","4","6",""};

var temp = new List<string>();
foreach (var s in URL)
{
         if (!string.IsNullOrEmpty(s))
         {
              temp.Add(s);
}
URL = temp.ToArray();

Monday 1 July 2013

How to remove recent projects from Visual Studio Start Page

To remove the projects from the list, follow these steps:
  1. Close Visual Studio if it is running.
  2. Start the Registry Editor (run regedit).
    Registry Editor
  3. Navigate to this registry key:
    HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList
    Registry Editor 2
  4. Then delete the key that has the project you do not want to keep in the list.

Friday 28 June 2013

Visual Studio 2008 - Toolbar missing 'Release' / 'Debug' dropdown build configuration

It describes how to get this useful dropdown visible:
  1. In Visual Studio 2008, click “Tools” -> “Options”

  1. Under “Projects and Solutions” -> “General”, check “Show advanced build options”, and click “OK”
 
          2.Right click anywhere in the blank space of the toolbar and click “Customize…”

      
       3.In “Commands” tab, select “Build” in “Categories”.

4. Scroll the right listbox to the bottom and drag “Solution Configurations” to the toolbar

Tuesday 4 June 2013

C# - Equivalent to the function GetSetting() in VB .NET

Getsetting DLL Download

using Microsoft.Win32;


public static string GetSetting(string applicationName, string sectionName, string key, string valeurParDéfaut)
        {
            StringBuilder path;
            RegistryKey registryKey;

            path = new StringBuilder(@"Software\VB and VBA Program Settings");

            // Generate the path of the key
            if (string.IsNullOrEmpty(applicationName) == false)
            {
                path.Append('\\');
                path.Append(applicationName);

                if (string.IsNullOrEmpty(sectionName) == false)
                {
                    path.Append('\\');
                    path.Append(sectionName);
                }
            }
            // Open key
            registryKey = Registry.CurrentUser.OpenSubKey(path.ToString());


            // If the key does not exist, return the default Open key
            if (registryKey == null)
            {
                return valeurParDéfaut;
            }
            try
            {
                //Read the value contained in the key
                return (string)registryKey.GetValue(key, valeurParDéfaut);
            }
            finally
            {
                //registryKey.Dispose();
            }
        }

public static string GetSetting(string applicationName, string sectionName, string key)
        {
            return GetSetting(applicationName, sectionName, key, null);
        }


//It is now possible to use this class like this:
string s;
            s= Getsetting.Form1.GetSetting("JRFleetini", "DatabasePathini", "dbPathini", null);
            MessageBox.Show(s);

Friday 24 May 2013

textbox - wait for user to finish typing in a Text Box

private void txtBusinessName_TextChanged(object sender, EventArgs e)
{
            TimerKey = 3000;
            timer1.Interval = TimerKey;
            timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
          SearchFirstTextbox();
            timer1.Enabled = false;
}

public void SearchFirstTextbox()
{
           string searchList = "<sreacn Key Word>";
            int col = 1;
            int colCount = col + 1;

            for (int lvelist = 0; lvelist < listview1.Items.Count; lvelist++)
            {
                if (listview1.Items[lvelist].Text.ToLower().Contains(searchList.ToLower()))
                {
                    listview1.TopItem = lvwClientInformation.Items[lvelist];
                    listview1.Items[lvelist].Selected = true;
                    listview1.Select();
                    lvelist = listview1.Items.Count;
                }
}

Thursday 23 May 2013

Display Time with the DateTimePicker Control

Display Time with the DateTimePicker Control

datetimePicker.Format = DateTimePickerFormat.Time;
datetimePicker.ShowUpDown = true; 

Comobo Box Hide / Not Type (Key press)

Solutions :  
private void ComoboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
            e.Handled = true;
}

shortcuts in C# Windows Form

Solutions :   

private void frmPartsFormWizard_KeyDown(object sender, KeyEventArgs e)
{
            if (Control.ModifierKeys == Keys.Alt && e.KeyCode == Keys.S)
            {
                txtbox1.Focus();
            }
            else if (Control.ModifierKeys == Keys.Alt && e.KeyCode == Keys.R)
            {
                txtbox2.Focus();
            }
}

Wednesday 22 May 2013

string[] remove null (string array remove Null)

string[] items = new string[]
{ "", "Name1", "Name2", null, "Name3", "Name4", null, "Name5" };
 
Solutions :   
items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray(); 

Friday 17 May 2013

How check if the form is already open

using System.Windows.Forms;

FormCollection fc = Application.OpenForms;
For (int FrmCount = 0; FrmCount < fc.Count; FrmCount++)
{
    Form frm = fc[FrmCount];
    if (frm.Name == "<Form Name>")
    {
       MessageBox.Show(" Child Forms Open");
    }
}

Tuesday 14 May 2013

ListView Column wise Sort

private void Listview1_ColumnClick(object sender, ColumnClickEventArgs e)
{
     this.Listview1.ListViewItemSorter = new ListViewItemComparer(e.Column);
}
class ListViewItemComparer : IComparer
        {
            private int col;
            public ListViewItemComparer()
            {
                col = 0;
            }
            public ListViewItemComparer(int column)
            {
                col = column;
            }
            public int Compare(object x, object y)
            {
                return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            }
        }

Copy data copy/paste to DataGridView use C#

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.C:
                            CopyToClipboard();
                            break;

                        case Keys.V:
                            PasteClipboard();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Copy/paste operation failed. " + ex.Message, "Copy/Paste", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

private void CopyToClipboard()
        {
            //Copy to clipboard
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
        }

private void PasteClipboard()
        {
            try
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split('\n');

                int iRow = dataGridView1.CurrentCell.RowIndex;
                int iCol = dataGridView1.CurrentCell.ColumnIndex;
                DataGridViewCell oCell;
                if (iRow + lines.Length > dataGridView1.Rows.Count - 1)
                {
                    bool bFlag = false;
                    foreach (string sEmpty in lines)
                    {
                        if (sEmpty == "")
                        {
                            bFlag = true;
                        }
                    }

                    int iNewRows = iRow + lines.Length - dataGridView1.Rows.Count;
                    if (iNewRows > 0)
                    {
                        if (bFlag)
                            dataGridView1.Rows.Add(iNewRows);
                        else
                            dataGridView1.Rows.Add(iNewRows + 1);
                    }
                    else
                        dataGridView1.Rows.Add(iNewRows + 1);
                }
                foreach (string line in lines)
                {
                    if (iRow < dataGridView1.RowCount && line.Length > 0)
                    {
                        string[] sCells = line.Split('\t');
                        for (int i = 0; i < sCells.GetLength(0); ++i)
                        {
                            if (iCol + i < this.dataGridView1.ColumnCount)
                            {
                                oCell = dataGridView1[iCol + i, iRow];
                                oCell.Value = Convert.ChangeType(sCells[i].Replace("\r", ""), oCell.ValueType);
                            }
                            else
                            {
                                break;
                            }
                        }
                        iRow++;
                    }
                    else
                    {
                        break;
                    }
                }
                Clipboard.Clear();
            }
            catch (FormatException)
            {
                MessageBox.Show("The data you pasted is in the wrong format for the cell");
                return;
            }
        }

Monday 29 April 2013

Get list of network computer Names and IP Address using C#

using System.Net.NetworkInformation;
using System.Net;
NetworkBrowser nb1 = new NetworkBrowser();
string[] PCIP = new string[250];
string[] PCIP1 = new string[250];
int i = 0;
foreach (string pc in nb1.getNetworkComputers())
{
    PCIP[i] = pc;
   IPAddress[] addresslist = Dns.GetHostAddresses(pc);
    foreach (IPAddress address in addresslist)
   {
        PCIP1[i] = address.ToString();                       
    }
    i++;
}

Get list of network computer names using C#

//get Network Computers Name
// Use using System.Net.NetworkInformation;


using System.Net.NetworkInformation;
NetworkBrowser nb1 = new NetworkBrowser();
string[] PCIP = new string[250];
int i = 0;
foreach (string pc in nb1.getNetworkComputers())
{
    PCIP[i] = pc;
    i++;
}

Thursday 14 March 2013

Calling code behind function from a html button

HTML button click call code behind in asp.net



<input type="button" id="btnuplod" runat="server" value="Upload" onclick="__doPostBack('btnSubmit','Submit');">

Code Behind
 
protected void Page_Load(object sender, EventArgs e)
{
   if (IsPostBack)
   {
      if (Convert.ToString(Request.Form["__EVENTARGUMENT"]) == "Submit")
      {
          btnuplod_Click();//submit action here
      }
   }
}

Your Function


Public void btnuplod_Click()
{
      if (FileUploadPDF.HasFile)
        {
            string fileName = Server.HtmlEncode(FileUpload1.FileName);
            string extension = System.IO.Path.GetExtension(fileName);
            if (extension == ".pdf")
            {

            }
            else
            {
                lblerror.InnerText = "Please upload PDF Files Only";
            }
        }
}