1. 程式人生 > 實用技巧 >一個帶有工具提示的列表框

一個帶有工具提示的列表框

介紹 我在做一個專案,我需要一個列表框來顯示 不適合於列表框寬度的專案的工具提示。 一開始我以為會有一個。net BCL類會有這個 設施。過去我有過一些讓我忘記的經歷,在那裡我浪費了很多時間 寫一些現成的東西。但這次我什麼也沒發現 符合我的要求。所以我寫了我自己的列表框類派生自。net System.Windows.Forms。ListBox類並呼叫它 ToolTipListBox。 它所做的 中的項 ToolTipListBox列表框超過了列表框的寬度 控制元件時,工具提示將懸浮在專案上。工具提示只浮動 用於不適合列表框寬度的專案。適合的物品 在,工具提示將不會顯示。 使用它 屬性的成員即可宣告列表框物件 ToolTipListBox類,而不是標準的ListBox類。 這是所有。你還必須包括 ToolTipListBox類原始檔。或者你 甚至可以構建一個庫並引用它。 類原始碼清單 隱藏,收縮,複製Code

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;


public class ToolTipListBox : System.Windows.Forms.ListBox
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SIZE
    {
        public
int cx; public int cy; } [DllImport("gdi32.dll")] public static extern int GetTextExtentPoint32(IntPtr hdc, String str, int len, ref SIZE size); [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static
extern int ReleaseDC(IntPtr hWnd,IntPtr hdc); public ToolTipListBox() { tp.InitialDelay = 500; tp.ReshowDelay = 500; tp.AutoPopDelay = 3000; tp.Active = true; } protected override void OnMouseMove( System.Windows.Forms.MouseEventArgs e) { /* Get the index of the mouse-hovered item */ int index = IndexFromPoint(e.X,e.Y); /* Ensure that there is an item */ if(index != ListBox.NoMatches ) { /* Check if the mouse has moved enough distance for a new index */ if( LastIndex != index ) { string s = Items[index].ToString(); /* Get the text extent */ IntPtr hdc = GetDC(this.Handle); SIZE size; size.cx = 0; size.cy = 0; GetTextExtentPoint32(hdc,s,s.Length,ref size); ReleaseDC(this.Handle,hdc); /* If it won't fit show tool-tip */ if(this.Width < size.cx) tp.SetToolTip(this,s); LastIndex = index; } } } private ToolTip tp = new ToolTip(); private int LastIndex = -1; }

本文轉載於:http://www.diyabc.com/frontweb/news344.html