在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → c# 获取当前系统所有窗口句柄(含任务栏/托盘图标等) 完整源码下载

c# 获取当前系统所有窗口句柄(含任务栏/托盘图标等) 完整源码下载

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.09M
  • 下载次数:180
  • 浏览次数:5492
  • 发布时间:2013-09-14
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: C# 托盘

实例介绍

【实例简介】

【实例截图】

【核心代码】

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 );
		}

	}
}

标签: C# 托盘

实例下载地址

c# 获取当前系统所有窗口句柄(含任务栏/托盘图标等) 完整源码下载

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 想的很单纯 发表于: 2018-05-29 15:29 46
win7不支持,要自己改

支持(0) 盖楼(回复)

第 2 楼 WY武帝 发表于: 2020-11-30 20:32 16
太老了,用不了了

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有2条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警