Click here to Skip to main content
15,893,381 members
Articles / Desktop Programming / Windows Forms

A tool to order the window buttons in your taskbar

Rate me:
Please Sign up or sign in to vote.
4.91/5 (54 votes)
9 Aug 2005CPOL8 min read 254.3K   7.1K   108  
Move your window buttons into your preferred order. WinXP or later only.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Reflection;
using System.Globalization;
using System.Diagnostics;

using Common;

namespace TaskbarSorter
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.TreeListView treeListView1;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.ComponentModel.IContainer components;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.ColumnHeader columnHeader3;
		private System.Windows.Forms.ColumnHeader columnHeader4;
		private System.Windows.Forms.ToolBarButton toolBarButtonMoveFirst;
		private System.Windows.Forms.ToolBarButton toolBarButtonMoveUp;
		private System.Windows.Forms.ImageList imageListToolbar;
		private System.Windows.Forms.ToolBarButton toolBarButtonMoveDown;
		private System.Windows.Forms.ToolBarButton toolBarButtonMoveLast;
		private System.Windows.Forms.Button _Apply;
		private System.Windows.Forms.Button _ViewTree;
		private System.Windows.Forms.Button _ExpandAll;
		private System.Windows.Forms.Button _CollapseAll;
		private System.Windows.Forms.ImageList imageListTreeView;
		private System.Windows.Forms.Button _Repair;
		private System.Windows.Forms.ToolTip _ToolTips;

		private Icon _Icon = null;

		private bool _FirstActivation = true;

		private ITree _Tree = NodeTree.NewTree( typeof( DataBase ) );

		private IntPtr _ToolbarWindowHandle = IntPtr.Zero;

		private bool _Glomming = true;

		public Form1()
		{
			string[] a = Assembly.GetEntryAssembly().GetManifestResourceNames();
			Trace.WriteLine( "\nResourceNames:" );
			foreach ( string s in a ) Trace.WriteLine( "\t" + s );
			Trace.WriteLine( "" );

			InitializeComponent();
		}

		protected override void OnHandleCreated( EventArgs e )
		{
			base.OnHandleCreated( e );

			UInt32 hIcon = User32.GetClassLong( Handle, GCL.HICONSM );

			if ( hIcon == 0 )
			{
				if ( _Icon == null ) _Icon = new Icon( typeof( Form1 ), "Icons.App.ico" );

				User32.SetClassLong( Handle, GCL.HICONSM, ( UInt32 ) _Icon.Handle );
			}
		}


		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#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.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
			this.button1 = new System.Windows.Forms.Button();
			this.toolBar1 = new System.Windows.Forms.ToolBar();
			this.toolBarButtonMoveFirst = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonMoveUp = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonMoveDown = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonMoveLast = new System.Windows.Forms.ToolBarButton();
			this.imageListToolbar = new System.Windows.Forms.ImageList(this.components);
			this.treeListView1 = new System.Windows.Forms.TreeListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
			this.imageListTreeView = new System.Windows.Forms.ImageList(this.components);
			this._Apply = new System.Windows.Forms.Button();
			this._ViewTree = new System.Windows.Forms.Button();
			this._ExpandAll = new System.Windows.Forms.Button();
			this._CollapseAll = new System.Windows.Forms.Button();
			this._Repair = new System.Windows.Forms.Button();
			this._ToolTips = new System.Windows.Forms.ToolTip(this.components);
			this.SuspendLayout();
			// 
			// button1
			// 
			this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.button1.Location = new System.Drawing.Point(8, 32);
			this.button1.Name = "button1";
			this.button1.TabIndex = 1;
			this.button1.Text = "Refresh";
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// toolBar1
			// 
			this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
			this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
																						this.toolBarButtonMoveFirst,
																						this.toolBarButtonMoveUp,
																						this.toolBarButtonMoveDown,
																						this.toolBarButtonMoveLast});
			this.toolBar1.DropDownArrows = true;
			this.toolBar1.ImageList = this.imageListToolbar;
			this.toolBar1.Location = new System.Drawing.Point(0, 0);
			this.toolBar1.Name = "toolBar1";
			this.toolBar1.ShowToolTips = true;
			this.toolBar1.Size = new System.Drawing.Size(592, 28);
			this.toolBar1.TabIndex = 0;
			this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
			// 
			// toolBarButtonMoveFirst
			// 
			this.toolBarButtonMoveFirst.ImageIndex = 0;
			this.toolBarButtonMoveFirst.ToolTipText = "Move First";
			// 
			// toolBarButtonMoveUp
			// 
			this.toolBarButtonMoveUp.ImageIndex = 1;
			this.toolBarButtonMoveUp.ToolTipText = "Move Up";
			// 
			// toolBarButtonMoveDown
			// 
			this.toolBarButtonMoveDown.ImageIndex = 2;
			this.toolBarButtonMoveDown.ToolTipText = "Move Down";
			// 
			// toolBarButtonMoveLast
			// 
			this.toolBarButtonMoveLast.ImageIndex = 3;
			this.toolBarButtonMoveLast.ToolTipText = "Move Last";
			// 
			// imageListToolbar
			// 
			this.imageListToolbar.ImageSize = new System.Drawing.Size(16, 16);
			this.imageListToolbar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListToolbar.ImageStream")));
			this.imageListToolbar.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// treeListView1
			// 
			this.treeListView1.AllowColumnReorder = true;
			this.treeListView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.treeListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																							this.columnHeader1,
																							this.columnHeader2,
																							this.columnHeader3,
																							this.columnHeader4});
			this.treeListView1.HideSelection = false;
			this.treeListView1.Location = new System.Drawing.Point(8, 64);
			this.treeListView1.MultiSelect = false;
			this.treeListView1.Name = "treeListView1";
			this.treeListView1.Size = new System.Drawing.Size(572, 392);
			this.treeListView1.SmallImageList = this.imageListTreeView;
			this.treeListView1.Sorting = System.Windows.Forms.SortOrder.None;
			this.treeListView1.TabIndex = 6;
			this.treeListView1.DoubleClick += new System.EventHandler(this.treeListView1_DoubleClick);
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "Process / Window";
			this.columnHeader1.Width = 300;
			// 
			// columnHeader2
			// 
			this.columnHeader2.Text = "Windows";
			// 
			// columnHeader3
			// 
			this.columnHeader3.Text = "Window Handle";
			this.columnHeader3.Width = 100;
			// 
			// columnHeader4
			// 
			this.columnHeader4.Text = "Process Id";
			this.columnHeader4.Width = 90;
			// 
			// imageListTreeView
			// 
			this.imageListTreeView.ImageSize = new System.Drawing.Size(16, 16);
			this.imageListTreeView.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListTreeView.ImageStream")));
			this.imageListTreeView.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// _Apply
			// 
			this._Apply.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._Apply.Location = new System.Drawing.Point(96, 32);
			this._Apply.Name = "_Apply";
			this._Apply.TabIndex = 2;
			this._Apply.Text = "Apply";
			this._Apply.Click += new System.EventHandler(this._Apply_Click);
			// 
			// _ViewTree
			// 
			this._ViewTree.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._ViewTree.Location = new System.Drawing.Point(504, 32);
			this._ViewTree.Name = "_ViewTree";
			this._ViewTree.TabIndex = 5;
			this._ViewTree.Text = "View Tree";
			this._ViewTree.Click += new System.EventHandler(this._ViewTree_Click);
			// 
			// _ExpandAll
			// 
			this._ExpandAll.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._ExpandAll.Location = new System.Drawing.Point(200, 32);
			this._ExpandAll.Name = "_ExpandAll";
			this._ExpandAll.TabIndex = 3;
			this._ExpandAll.Text = "Expand All";
			this._ExpandAll.Click += new System.EventHandler(this._ExpandAll_Click);
			// 
			// _CollapseAll
			// 
			this._CollapseAll.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._CollapseAll.Location = new System.Drawing.Point(288, 32);
			this._CollapseAll.Name = "_CollapseAll";
			this._CollapseAll.TabIndex = 4;
			this._CollapseAll.Text = "Collapse All";
			this._CollapseAll.Click += new System.EventHandler(this._CollapseAll_Click);
			// 
			// _Repair
			// 
			this._Repair.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._Repair.Location = new System.Drawing.Point(416, 32);
			this._Repair.Name = "_Repair";
			this._Repair.TabIndex = 5;
			this._Repair.Text = "OS Version";
			this._ToolTips.SetToolTip(this._Repair, "Repair ToolTips");
			this._Repair.Click += new System.EventHandler(this._Repair_Click);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(592, 466);
			this.Controls.Add(this._ViewTree);
			this.Controls.Add(this._Apply);
			this.Controls.Add(this.treeListView1);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.toolBar1);
			this.Controls.Add(this._ExpandAll);
			this.Controls.Add(this._CollapseAll);
			this.Controls.Add(this._Repair);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "Form1";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Taskbar Sorter";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.Activated += new System.EventHandler(this.Form1_Activated);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
//		[ PrincipalPermission( SecurityAction.Demand, Authenticated = true ) ]
		static void Main() 
		{
			// only supports WinXP or later
			try
			{
				OperatingSystemVersion os = new OperatingSystemVersion();

				string s = os.ToString();

				if (
					os.OSPlatformId <= OSPlatformId.Win32Windows ||
					os.OSPlatformId == OSPlatformId.WinCE )
				{
					MessageBox.Show(
						"You must be joking :)",
						"Unsupported OS",
						MessageBoxButtons.OK,
						MessageBoxIcon.Stop );
				
					return;
				}

				if ( ( os < OSVersionInfo.WinXP ) )
				{
					MessageBox.Show(
						"This program only works on WinXP and later :)" +
						Environment.NewLine + Environment.NewLine +
						"You are running:" + Environment.NewLine + s,
						"Unsupported OS",
						MessageBoxButtons.OK,
						MessageBoxIcon.Stop );
				
					return;
				}
			}
			catch ( InvalidOperationException x )
			{
				MessageBox.Show(
					"Could not determine Operating System." +
					Environment.NewLine + Environment.NewLine +
					"Error:" + Environment.NewLine + x.Message,
					"Unknown OS",
					MessageBoxButtons.OK,
					MessageBoxIcon.Stop );
			
				return;
			}

			Application.EnableVisualStyles();
			Application.DoEvents();

			Application.Run(new Form1());
		}

		private void Form1_Load( object sender, System.EventArgs e )
		{
//			SYSTEM_INFO systemInfo;
//			Kernel32.GetSystemInfo( out systemInfo );

			// Displays a MessageBox if not found
			_ToolbarWindowHandle = GetToolbarWindowHandle();
			if ( _ToolbarWindowHandle == IntPtr.Zero ) Close();

			// true if grouping is on
			_Glomming = ( Glob.Glomming.Int != 0 );
		}

		private void Form1_Activated( object sender, System.EventArgs e )
		{
			if ( _FirstActivation )
			{
				_FirstActivation = false;

				button1_Click( this, EventArgs.Empty );
			}
		}

		private IntPtr GetToolbarWindowHandle()
		{
			IntPtr hDesktop = User32.GetDesktopWindow();

			IntPtr hTray = User32.FindWindowEx( hDesktop, IntPtr.Zero, "Shell_TrayWnd", null );

			IntPtr hReBar = User32.FindWindowEx( hTray, IntPtr.Zero, "ReBarWindow32", null );

			IntPtr hTask = User32.FindWindowEx( hReBar, IntPtr.Zero, "MSTaskSwWClass", null );

			IntPtr hToolbar = User32.FindWindowEx( hTask, IntPtr.Zero, "ToolbarWindow32", null );

//			hToolbar = User32.FindWindowEx( hReBar, IntPtr.Zero, "ToolbarWindow32", "Quick Launch" );

//			hToolbar = toolBar1.Handle;

			if ( hToolbar == IntPtr.Zero )
				MessageBox.Show(
					"Couldn't find Taskbar",
					"Error",
					MessageBoxButtons.OK,
					MessageBoxIcon.Error );

			return hToolbar;
		}

		private void button1_Click( object sender, System.EventArgs e )
		{
			treeListView1.Items.Clear();
			_Tree.Clear();

			_ToolbarWindowHandle = GetToolbarWindowHandle();
			if ( _ToolbarWindowHandle == IntPtr.Zero ) return;

			_Glomming = ( Glob.Glomming.Int != 0 );

			UInt32 count = User32.SendMessage( _ToolbarWindowHandle, TB.BUTTONCOUNT, 0, 0 );

			for ( int i = 0 ; i < count ; i++ )
			{
				TBBUTTON tbButton = new TBBUTTON();
				string text = String.Empty;
				IntPtr ipWindowHandle = IntPtr.Zero;

				bool b = GetTBButton( _ToolbarWindowHandle, i, ref tbButton, ref text, ref ipWindowHandle );

				if ( b ) AddData( tbButton, text, ipWindowHandle );
			}

			CreateImageList();

			FillTreeList();

//			User32.SendMessage( hToolbar, TB.CUSTOMIZE, IntPtr.Zero, IntPtr.Zero );
		}

		private void AddData( TBBUTTON tbButton, string text, IntPtr ipWindowHandle )
		{
			string state = ( ( tbButton.fsState & TBSTATE.HIDDEN ) == 0 ) ? "Shown" : "Hidden";
			string handle = "0x" + ( ( UInt32 ) ipWindowHandle ).ToString( "X8", CultureInfo.CurrentCulture );

			if ( _Glomming )
			{
				if ( ipWindowHandle == IntPtr.Zero ) // Process
				{
					DataProcess o = new DataProcess( tbButton, text, ipWindowHandle );
					o.Node = _Tree.AddChild( o );
				}
				else // Window
				{
					DataWindow o = new DataWindow( tbButton, text, ipWindowHandle );
					o.Node = _Tree.Root.Child.Last.AddChild( o );
				}
			}
			else // not glomming
			{
				if ( ipWindowHandle != IntPtr.Zero )
				{
					DataWindow o = new DataWindow( tbButton, text, ipWindowHandle );
					o.Node = _Tree.AddChild( o );
				}
			}
		}

		private void CreateImageList()
		{
			ImageList list = treeListView1.SmallImageList;

			ImageList.ImageCollection images = list.Images;
			while ( images.Count > 2 ) images.RemoveAt( 2 );

			foreach ( INode node in _Tree.AllChildren )
			{
				DataBase db = ( DataBase ) node.Data;

				if ( db.DataType == DataType.Window )
				{
					DataWindow window = ( DataWindow ) db;

					UInt32 hIcon = 0;
					if ( hIcon == 0 ) hIcon = User32.SendMessage  ( window.WindowHandle, WM.GETICON, ICON.SMALL2, 0 );
					if ( hIcon == 0 ) hIcon = User32.GetClassLong ( window.WindowHandle, GCL.HICONSM );
					if ( hIcon == 0 ) hIcon = User32.GetClassLong ( window.WindowHandle, GCL.HICON   );

					if ( hIcon == 0 ) continue;

					Bitmap bitmap = null;

					try
					{
						Int32 hIcon2 = unchecked ( ( Int32 ) hIcon );

						bitmap = Bitmap.FromHicon( new IntPtr( hIcon2 ) );
					}
					catch ( ArgumentException ) { continue; }

					if ( bitmap == null ) continue;

					images.Add( bitmap );
					int imageIndex = images.Count - 1;

					window.ImageIndex = imageIndex;

					if ( ! node.IsTop )
					{
						DataProcess process = ( DataProcess ) node.Parent.Data;

						process.ImageIndex = imageIndex;
					}
				}
			}
		}

		private void FillTreeList()
		{
			if ( _Glomming )
			{
				foreach ( INode nodeProcess in _Tree.Nodes )
				{
					DataProcess process = ( DataProcess ) nodeProcess.Data;

					string text = process.ButtonText;
					bool bNoName = ( text.Length == 0 );
					if ( bNoName ) text = "< no name >";

					TreeListViewItem itemProcess = new TreeListViewItem( text, process.ImageIndex );
					itemProcess.Tag = process;
					if ( bNoName ) itemProcess.Expand();
					itemProcess.SubItems.Add( nodeProcess.Nodes.Count.ToString( CultureInfo.CurrentCulture ) );
//					itemProcess.SubItems.Add( "0x" + ( ( UInt32 ) process.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) );
					treeListView1.Items.Add( itemProcess );

					foreach ( INode nodeWindow in nodeProcess.Nodes )
					{
						DataWindow window = ( DataWindow ) nodeWindow.Data;

						TreeListViewItem itemWindow = new TreeListViewItem( window.ButtonText, window.ImageIndex );
						itemWindow.Tag = window;
						itemWindow.SubItems.Add( String.Empty );
						itemWindow.SubItems.Add( "0x" + ( ( UInt32 ) window.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) );
						itemWindow.SubItems.Add( "0x" + ( ( UInt32 ) window.ProcessId    ).ToString( "X8", CultureInfo.CurrentCulture ) );
						itemProcess.Items.Add( itemWindow );
					}
				}
			}
			else // not glomming
			{
				foreach ( INode nodeWindow in _Tree.Nodes )
				{
					DataWindow window = ( DataWindow ) nodeWindow.Data;

					TreeListViewItem itemWindow = new TreeListViewItem( window.ButtonText, window.ImageIndex );
					itemWindow.Tag = window;
					itemWindow.SubItems.Add( String.Empty );
					itemWindow.SubItems.Add( "0x" + ( ( UInt32 ) window.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) );
					itemWindow.SubItems.Add( "0x" + ( ( UInt32 ) window.ProcessId    ).ToString( "X8", CultureInfo.CurrentCulture ) );
					treeListView1.Items.Add( itemWindow );
				}
			}
		}

		private void PopulateTreeFromList()
		{
			_Tree.Clear();

			foreach ( TreeListViewItem itemParent in treeListView1.Items )
			{
				DataBase dataParent = ( DataBase ) itemParent.Tag;

				INode nodeParent = dataParent.Node = _Tree.AddChild( dataParent );

				foreach ( TreeListViewItem itemChild in itemParent.Items )
				{
					DataBase dataChild = ( DataBase ) itemChild.Tag;

					INode nodeChild = dataChild.Node = nodeParent.AddChild( dataChild );
				}
			}
		}

		private unsafe bool GetTBButton( IntPtr hToolbar, int i, ref TBBUTTON tbButton, ref string text, ref IntPtr ipWindowHandle )
		{
			// One page
			const int BUFFER_SIZE = 0x1000;

			byte[] localBuffer = new byte[ BUFFER_SIZE ];

			UInt32 processId = 0;
			UInt32 threadId = User32.GetWindowThreadProcessId( hToolbar, out processId );

			IntPtr hProcess = Kernel32.OpenProcess( ProcessRights.ALL_ACCESS, false, processId );
			if ( hProcess == IntPtr.Zero ) { Debug.Assert( false ); return false; }
 
			IntPtr ipRemoteBuffer = Kernel32.VirtualAllocEx(
				hProcess,
				IntPtr.Zero,
				new UIntPtr( BUFFER_SIZE ),
				MemAllocationType.COMMIT,
				MemoryProtection.PAGE_READWRITE );

			if ( ipRemoteBuffer == IntPtr.Zero ) { Debug.Assert( false ); return false; }

			// TBButton
			fixed ( TBBUTTON* pTBButton = & tbButton )
			{
				IntPtr ipTBButton = new IntPtr( pTBButton );

				int b = ( int ) User32.SendMessage( hToolbar, TB.GETBUTTON, ( IntPtr ) i, ipRemoteBuffer );
				if ( b == 0 ) { Debug.Assert( false ); return false; }

				// this is fixed
				Int32 dwBytesRead = 0;
				IntPtr ipBytesRead = new IntPtr( & dwBytesRead );

				bool b2 = Kernel32.ReadProcessMemory(
					hProcess,
					ipRemoteBuffer,
					ipTBButton,
					new UIntPtr( ( uint ) sizeof( TBBUTTON ) ),
					ipBytesRead );

				if ( ! b2 ) { Debug.Assert( false ); return false; }
			}

			// button text
			fixed ( byte* pLocalBuffer = localBuffer )
			{
				IntPtr ipLocalBuffer = new IntPtr( pLocalBuffer );

				int chars = ( int ) User32.SendMessage( hToolbar, TB.GETBUTTONTEXTW, ( IntPtr ) tbButton.idCommand, ipRemoteBuffer );
				if ( chars == -1 ) { Debug.Assert( false ); return false; }

				// this is fixed
				Int32 dwBytesRead = 0;
				IntPtr ipBytesRead = new IntPtr( & dwBytesRead );

				bool b4 = Kernel32.ReadProcessMemory(
					hProcess,
					ipRemoteBuffer,
					ipLocalBuffer,
					new UIntPtr( BUFFER_SIZE ),
					ipBytesRead );

				if ( ! b4 ) { Debug.Assert( false ); return false; }

				text = Marshal.PtrToStringUni( ipLocalBuffer, chars );

				if ( text == " " ) text = String.Empty;
			}

			// window handle
			fixed ( byte* pLocalBuffer = localBuffer )
			{
				IntPtr ipLocalBuffer = new IntPtr( pLocalBuffer );

				// this is in the remote virtual memory space
				IntPtr ipRemoteData = new IntPtr( tbButton.dwData );

				// this is fixed
				Int32 dwBytesRead = 0;
				IntPtr ipBytesRead = new IntPtr( & dwBytesRead );

				bool b4 = Kernel32.ReadProcessMemory(
					hProcess,
					ipRemoteData,
					ipLocalBuffer,
					new UIntPtr( 4 ),
					ipBytesRead );

				if ( ! b4 ) { Debug.Assert( false ); return false; }

				if ( dwBytesRead != 4 ) { Debug.Assert( false ); return false; }

				Int32 iWindowHandle = BitConverter.ToInt32( localBuffer, 0 );
				if ( iWindowHandle == -1 ) { Debug.Assert( false ); }//return false; }

				ipWindowHandle = new IntPtr( iWindowHandle );
			}

			Kernel32.VirtualFreeEx(
				hProcess,
				ipRemoteBuffer,
				UIntPtr.Zero,
				MemAllocationType.RELEASE );

			Kernel32.CloseHandle( hProcess );

			return true;
		}

		private void _Apply_Click( object sender, System.EventArgs e )
		{
			using ( new CWaitCursor() )
			foreach ( int sw in new int[] { SW.HIDE, SW.SHOW } )
			{
				foreach ( DataBase db in _Tree.AllChildren.Values )
				{
					if ( db.DataType == DataType.Window )
					{
						DataWindow window = ( DataWindow ) db;

						IntPtr hWindow = window.WindowHandle;

						User32.ShowWindow( hWindow, sw );

//						if ( sw == SW.SHOW ) System.Threading.Thread.Sleep( 500 );
					}
				}

				System.Threading.Thread.Sleep( 500 );
			}

			User32.SetForegroundWindow( Handle );
		}

		private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			if ( e.Button == toolBarButtonMoveFirst ) OnMoveFirst ();
			if ( e.Button == toolBarButtonMoveUp    ) OnMoveUp    ();
			if ( e.Button == toolBarButtonMoveDown  ) OnMoveDown  ();
			if ( e.Button == toolBarButtonMoveLast  ) OnMoveLast  ();
		}

		private TreeListViewItemCollection GetItemCollection( TreeListViewItem item )
		{
			if ( item.Parent == null )
			{
				if ( item.TreeListView == null ) throw new ArgumentException( "TreeListView not set for this item" );

				return item.TreeListView.Items;
			}

			return item.Parent.Items;
		}

		private void OnMoveFirst()
		{
			// fubar
//			ListView.SelectedIndexCollection indices = treeListView1.SelectedIndices;
//			if ( indices.Count != 1 ) return;
//			int index = indices[ 0 ];

			SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;
			if ( items.Count != 1 ) return;
			TreeListViewItem item = items[ 0 ];

			MoveFirst( item );

			item.Selected = true;

			PopulateTreeFromList();
		}

		private void MoveFirst( TreeListViewItem item )
		{
			DataBase db = ( DataBase ) item.Tag;

			int index = db.Node.IndexBranch;
			if ( index == 0 ) return;

			TreeListViewItemCollection items = GetItemCollection( item );

			TreeListViewItemCollection items2 = new TreeListViewItemCollection();
			items2.SortOrder = SortOrder.None;
			foreach( TreeListViewItem item2 in items )
				if ( item2 != item )
					items2.Add( item2 );

			items.Clear();

			for ( int i = 0 ; i < items2.Count ; i++ )
			{
				if ( i == 0 ) items.Add( item );

				items.Add( items2[ i ] );
			}
		}

		private void OnMoveUp()
		{
			// fubar
//			ListView.SelectedIndexCollection indices = treeListView1.SelectedIndices;
//			if ( indices.Count != 1 ) return;
//			int index = indices[ 0 ];

			SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;
			if ( items.Count != 1 ) return;
			TreeListViewItem item = items[ 0 ];

			MoveUp( item );

			item.Selected = true;

			PopulateTreeFromList();
		}

		private void MoveUp( TreeListViewItem item )
		{
			DataBase db = ( DataBase ) item.Tag;

			int index = db.Node.IndexBranch;
			if ( index == 0 ) return;

			TreeListViewItemCollection items = GetItemCollection( item );

			TreeListViewItemCollection items2 = new TreeListViewItemCollection();
			items2.SortOrder = SortOrder.None;
			foreach( TreeListViewItem item2 in items )
				if ( item2 != item )
					items2.Add( item2 );

			items.Clear();

			for ( int i = 0 ; i < items2.Count ; i++ )
			{
				if ( i == index - 1 ) items.Add( item );

				items.Add( items2[ i ] );
			}
		}


		private void OnMoveDown()
		{
			// fubar
//			ListView.SelectedIndexCollection indices = treeListView1.SelectedIndices;
//			if ( indices.Count != 1 ) return;
//			int index = indices[ 0 ];

			SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;
			if ( items.Count != 1 ) return;
			TreeListViewItem item = items[ 0 ];

			MoveDown( item );

			item.Selected = true;

			PopulateTreeFromList();
		}

		private void MoveDown( TreeListViewItem item )
		{
			DataBase db = ( DataBase ) item.Tag;

			int index = db.Node.IndexBranch;
			if ( db.Node.IsLast ) return;

			TreeListViewItemCollection items = GetItemCollection( item );

			TreeListViewItemCollection items2 = new TreeListViewItemCollection();
			items2.SortOrder = SortOrder.None;
			foreach( TreeListViewItem item2 in items )
				if ( item2 != item )
					items2.Add( item2 );

			items.Clear();

			for ( int i = 0 ; i < items2.Count ; i++ )
			{
				items.Add( items2[ i ] );

				if ( i == index ) items.Add( item );
			}
		}

		private void OnMoveLast()
		{
			// fubar
//			ListView.SelectedIndexCollection indices = treeListView1.SelectedIndices;
//			if ( indices.Count != 1 ) return;
//			int index = indices[ 0 ];

			SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;
			if ( items.Count != 1 ) return;
			TreeListViewItem item = items[ 0 ];

			MoveLast( item );

			item.Selected = true;

			PopulateTreeFromList();
		}

		private void MoveLast( TreeListViewItem item )
		{
			DataBase db = ( DataBase ) item.Tag;

			int index = db.Node.IndexBranch;
			if ( db.Node.IsLast ) return;

			TreeListViewItemCollection items = GetItemCollection( item );

			TreeListViewItemCollection items2 = new TreeListViewItemCollection();
			items2.SortOrder = SortOrder.None;
			foreach( TreeListViewItem item2 in items )
				if ( item2 != item )
					items2.Add( item2 );

			items.Clear();

			for ( int i = 0 ; i < items2.Count ; i++ )
			{
				items.Add( items2[ i ] );
			}

			items.Add( item );
		}

		private void _ExpandAll_Click(object sender, System.EventArgs e)
		{
			treeListView1.ExpandAll();
		}

		private void _CollapseAll_Click(object sender, System.EventArgs e)
		{
			treeListView1.CollapseAll();
		}

		private void _ViewTree_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show( _Tree.ToStringRecursive(), "_Tree" );
		}

		private void treeListView1_DoubleClick( object sender, System.EventArgs e )
		{
			SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;
			if ( items.Count != 1 ) return;
			TreeListViewItem item = items[ 0 ];

			DataBase db = ( DataBase ) item.Tag;

			if ( db.DataType != DataType.Window ) return;

			DataWindow window = ( DataWindow ) db;

			User32.SetForegroundWindow( window.WindowHandle );
		}

		private void _Repair_Click( object sender, System.EventArgs e )
		{
			OperatingSystemVersion os = new OperatingSystemVersion();
			string sOS = os.ToString();

			string sMem = String.Empty;
			MEMORYSTATUSEX m = new MEMORYSTATUSEX();
			if ( Kernel32.GlobalMemoryStatusEx( m ) )
			{
				const int MB = 1024 * 1024;

				UInt64 total = m.TotalPhysical;
				UInt64 free  = m.AvailablePhysical;
				UInt64 used  = total - free;
				UInt64 freePercent = ( 100 * free ) / total;
				UInt64 usedPercent = ( 100 * used ) / total;

				sMem =
					"Memory\n" + // ( Load : " + m.MemoryLoad + " % )\n" +
					"---------------------\n" +
					"Physical\t : " + ( total / MB ) + " MB\n" +
					"Used    \t : " + ( used  / MB ) + " MB ( " + usedPercent + " % )\n" +
					"Free    \t : " + ( free  / MB ) + " MB ( " + freePercent + " % )\n"; 
			}

			MessageBox.Show(
				"You are running :" +
				Environment.NewLine + Environment.NewLine + sOS +
				Environment.NewLine + Environment.NewLine + sMem,
				"Supported OS",
				MessageBoxButtons.OK,
				MessageBoxIcon.Information );
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
I discovered C# and .NET 1.0 Beta 1 in late 2000 and loved them immediately.
I have been writing software professionally in C# ever since

In real life, I have spent 3 years travelling abroad,
I have held a UK Private Pilots Licence for 20 years,
and I am a PADI Divemaster.

I now live near idyllic Bournemouth in England.

I can work 'virtually' anywhere!

Comments and Discussions