//------------------------------------------------------------------------------
/// <copyright from='2004' to='2005' company='Christian Forsberg'>
///		Copyright (c) Christian Forsberg, chris@businessanyplace.net.
///
///   This program is distributed in the hope that it will be useful,
///   but WITHOUT ANY WARRANTY; without even the implied warranty of
///   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;

namespace TaskManager
{
  /// <summary>
	/// This is the main form.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
    private Window[] windows;
    private Process[] processes;

    #region Windows Form Designer generated declarations
    private System.Windows.Forms.MainMenu mainMenu;
    private System.Windows.Forms.MenuItem menuMenuItem;
    private System.Windows.Forms.ListView listView;
    private System.Windows.Forms.ColumnHeader itemsColumnHeader;
    private System.Windows.Forms.MenuItem aboutMenuItem;
    private System.Windows.Forms.MenuItem refreshMenuItem;
    private System.Windows.Forms.MenuItem killMenuItem;
    private System.Windows.Forms.MenuItem stopMenuItem;
    private System.Windows.Forms.MenuItem stopAllMenuItem;
    private System.Windows.Forms.MenuItem processesMenuItem;
    private System.Windows.Forms.MenuItem activateMenuItem;
    private System.Windows.Forms.MenuItem doneMenuItem;
    private System.Windows.Forms.MenuItem viewMenuItem;
    #endregion

    #region Constructor
		public MainForm()
		{
			InitializeComponent();
		}
    #endregion

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.mainMenu = new System.Windows.Forms.MainMenu();
            this.activateMenuItem = new System.Windows.Forms.MenuItem();
            this.menuMenuItem = new System.Windows.Forms.MenuItem();
            this.refreshMenuItem = new System.Windows.Forms.MenuItem();
            this.processesMenuItem = new System.Windows.Forms.MenuItem();
            this.stopMenuItem = new System.Windows.Forms.MenuItem();
            this.stopAllMenuItem = new System.Windows.Forms.MenuItem();
            this.viewMenuItem = new System.Windows.Forms.MenuItem();
            this.killMenuItem = new System.Windows.Forms.MenuItem();
            this.aboutMenuItem = new System.Windows.Forms.MenuItem();
            this.doneMenuItem = new System.Windows.Forms.MenuItem();
            this.listView = new System.Windows.Forms.ListView();
            this.itemsColumnHeader = new System.Windows.Forms.ColumnHeader();
            this.SuspendLayout();
            // 
            // mainMenu
            // 
            this.mainMenu.MenuItems.Add(this.activateMenuItem);
            this.mainMenu.MenuItems.Add(this.menuMenuItem);
            // 
            // activateMenuItem
            // 
            this.activateMenuItem.Text = "Перейти в ...";
            this.activateMenuItem.Click += new System.EventHandler(this.activateMenuItem_Click);
            // 
            // menuMenuItem
            // 
            this.menuMenuItem.MenuItems.Add(this.refreshMenuItem);
            this.menuMenuItem.MenuItems.Add(this.processesMenuItem);
            this.menuMenuItem.MenuItems.Add(this.stopMenuItem);
            this.menuMenuItem.MenuItems.Add(this.stopAllMenuItem);
            this.menuMenuItem.MenuItems.Add(this.viewMenuItem);
            this.menuMenuItem.MenuItems.Add(this.killMenuItem);
            this.menuMenuItem.MenuItems.Add(this.aboutMenuItem);
            this.menuMenuItem.MenuItems.Add(this.doneMenuItem);
            this.menuMenuItem.Text = "Меню";
            this.menuMenuItem.Popup += new System.EventHandler(this.menuMenuItem_Popup);
            // 
            // refreshMenuItem
            // 
            this.refreshMenuItem.Text = "Обновить";
            this.refreshMenuItem.Click += new System.EventHandler(this.refreshMenuItem_Click);
            // 
            // processesMenuItem
            // 
            this.processesMenuItem.Text = "Процессы";
            this.processesMenuItem.Click += new System.EventHandler(this.processesMenuItem_Click);
            // 
            // stopMenuItem
            // 
            this.stopMenuItem.Text = "Остановить";
            this.stopMenuItem.Click += new System.EventHandler(this.stopMenuItem_Click);
            // 
            // stopAllMenuItem
            // 
            this.stopAllMenuItem.Text = "Остановить все";
            this.stopAllMenuItem.Click += new System.EventHandler(this.stopAllMenuItem_Click);
            // 
            // viewMenuItem
            // 
            this.viewMenuItem.Text = "Вид";
            this.viewMenuItem.Click += new System.EventHandler(this.viewMenuItem_Click);
            // 
            // killMenuItem
            // 
            this.killMenuItem.Text = "Убить";
            this.killMenuItem.Click += new System.EventHandler(this.killMenuItem_Click);
            // 
            // aboutMenuItem
            // 
            this.aboutMenuItem.Text = "О программе";
            this.aboutMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click);
            // 
            // doneMenuItem
            // 
            this.doneMenuItem.Text = "Готово";
            this.doneMenuItem.Click += new System.EventHandler(this.doneMenuItem_Click);
            // 
            // listView
            // 
            this.listView.Columns.Add(this.itemsColumnHeader);
            this.listView.FullRowSelect = true;
            this.listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            this.listView.Location = new System.Drawing.Point(-1, -1);
            this.listView.Name = "listView";
            this.listView.Size = new System.Drawing.Size(178, 182);
            this.listView.TabIndex = 0;
            this.listView.View = System.Windows.Forms.View.Details;
            // 
            // itemsColumnHeader
            // 
            this.itemsColumnHeader.Text = "Items";
            this.itemsColumnHeader.Width = 170;
            // 
            // MainForm
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.ClientSize = new System.Drawing.Size(176, 180);
            this.Controls.Add(this.listView);
            this.Menu = this.mainMenu;
            this.Name = "MainForm";
            this.Text = "Диспетчер задач";
            this.Activated += new System.EventHandler(this.MainForm_Activated);
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.ResumeLayout(false);

    }
		#endregion

    #region Main
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main() 
		{
			Application.Run(new MainForm());
		}
    #endregion

 
    private void MainForm_Load(object sender, System.EventArgs e)
    {
      ListViewHelper.SetGradient(listView);
      mainMenu.MenuItems[1].MenuItems.Remove(viewMenuItem);
      mainMenu.MenuItems[1].MenuItems.Remove(killMenuItem);
    }

    private void MainForm_Activated(object sender, EventArgs e)
    {
      fillList();
    }


    private void fillList()
    {
      if(activateMenuItem.Text == "Перейти в ...")
        fillTaskList();
      else
        fillProcessList();
    }

    private void fillTaskList()
    {
      Cursor.Current = Cursors.WaitCursor;

      // Получим список запущенных приложений
      windows = WindowHelper.EnumerateTopWindows();

      // Заполняем ListView
      ListViewItem lvi;
      listView.BeginUpdate();
      listView.Items.Clear();
      foreach(Window w in windows)
      {
        lvi = new ListViewItem(w.ToString());
        listView.Items.Add(lvi);
      }
      listView.EndUpdate();
      if(listView.Items.Count > 0)
      {
        listView.Items[0].Selected = true;
        listView.Items[0].Focused = true;
      }
      Cursor.Current = Cursors.Default;
    }

    private void fillProcessList()
    {
      Cursor.Current = Cursors.WaitCursor;

      // Получаем список запущенных процессов
      processes = Process.GetProcesses();

      // Заполняем ListView
      ListViewItem lvi;
      listView.BeginUpdate();
      listView.Items.Clear();
      foreach(Process p in processes)
      {
        lvi = new ListViewItem(p.ProcessName);
        //lvi.SubItems.Add("ID");
        listView.Items.Add(lvi);
      }
      listView.EndUpdate();
      if(listView.Items.Count > 0)
      {
        listView.Items[0].Selected = true;
        listView.Items[0].Focused = true;
      }
      Cursor.Current = Cursors.Default;
    }
 

    #region Menu options
    private void activateMenuItem_Click(object sender, System.EventArgs e)
    {
      if(activateMenuItem.Text == "Done")
      {
        this.Text = "Task Manager";
        activateMenuItem.Text = "Activate";
        mainMenu.MenuItems[1].MenuItems.Remove(viewMenuItem);
        mainMenu.MenuItems[1].MenuItems.Remove(killMenuItem);
        mainMenu.MenuItems[1].MenuItems.Remove(aboutMenuItem);
        mainMenu.MenuItems[1].MenuItems.Add(processesMenuItem);
        mainMenu.MenuItems[1].MenuItems.Add(stopMenuItem);
        mainMenu.MenuItems[1].MenuItems.Add(stopAllMenuItem);
        mainMenu.MenuItems[1].MenuItems.Add(aboutMenuItem);
        mainMenu.MenuItems[1].MenuItems.Add(doneMenuItem);
        fillList();
      }
      else
      {
        if(listView.SelectedIndices.Count > 0)
          WindowHelper.ActivateWindow(windows[listView.SelectedIndices[0]].Handle);
        this.Close();
      }
    }

    private void menuMenuItem_Popup(object sender, System.EventArgs e)
    {
      bool onItem = listView.SelectedIndices.Count > 0;
      stopMenuItem.Enabled = onItem;
      viewMenuItem.Enabled = onItem;
      killMenuItem.Enabled = onItem;
    }

    private void processesMenuItem_Click(object sender, System.EventArgs e)
    {
      this.Text = "Processes";
      activateMenuItem.Text = "Done";
      mainMenu.MenuItems[1].MenuItems.Remove(processesMenuItem);
      mainMenu.MenuItems[1].MenuItems.Remove(stopMenuItem);
      mainMenu.MenuItems[1].MenuItems.Remove(stopAllMenuItem);
      mainMenu.MenuItems[1].MenuItems.Remove(aboutMenuItem);
      mainMenu.MenuItems[1].MenuItems.Remove(doneMenuItem);
      mainMenu.MenuItems[1].MenuItems.Add(viewMenuItem);
      mainMenu.MenuItems[1].MenuItems.Add(killMenuItem);
      mainMenu.MenuItems[1].MenuItems.Add(aboutMenuItem);
      fillList();
    }

    private void refreshMenuItem_Click(object sender, System.EventArgs e)
    {
      fillList();
    }

    private void stopMenuItem_Click(object sender, System.EventArgs e)
    {
      WindowHelper.CloseWindow(windows[listView.SelectedIndices[0]].Handle);
      fillList();
    }

    private void stopAllMenuItem_Click(object sender, System.EventArgs e)
    {
      WindowHelper.CloseApps();
      fillList();
      //foreach(Window w in windows)
      //  SendMessage(w.Handle, WM_CLOSE, 0, 0);
    }

    private void viewMenuItem_Click(object sender, System.EventArgs e)
    {
      Cursor.Current = Cursors.WaitCursor;
      Process p = processes[listView.SelectedIndices[0]];
      ProcessForm processForm = new ProcessForm(this, p.ProcessName, p.ProcessId, p.ThreadCount, p.BaseAddress);
      DialogResult dr = processForm.ShowDialog();
      listView.Focus();
    }

    private void killMenuItem_Click(object sender, System.EventArgs e)
    {
      Process p = processes[listView.SelectedIndices[0]];
      p.Kill();
      fillList();
    }

    private void aboutMenuItem_Click(object sender, System.EventArgs e)
    {
      MessageBox.Show("Task Manager 1.0\n\nCopyright (c)2005 Christian Forsberg, chris@businessanyplace.net.", "About",
        MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
    }

    private void doneMenuItem_Click(object sender, System.EventArgs e)
    {
      this.Close();
    }
    #endregion

    #region IDisposable members
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      base.Dispose( disposing );
    }
    #endregion
  }
}
