实现IE7的搜索框效果

不光是IE7, 这种搜索框在VISTA上到处可见。它的特点是用浅灰色显示提示信息,在用户开始输入时变成正常的TextBox。用户再次离开该输入框时, 如果刚才输入了内容则显示输入的内容,没有输入则继续显示提示信息。这个主要涉及到获得和失去焦点的事件的处理。

先定义两个不同的字体来表示提示信息和正常输入的区别。

Font regularFont;
Font ItalicFont;

初始化它们

regularFont = this.toolStripTextBoxSearch.Font;
ItalicFont = new Font(regularFont, FontStyle.Italic);

toolStripTextBoxSearch就是要操作的TextBox.

添加对Enter和Leave事件的处理

private void toolStripTextBoxSearch_Enter(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(searchContent))
            {
                HideSearchContent();
            }
        }

        private void HideSearchContent()
        {
            this.toolStripTextBoxSearch.Text = String.Empty;
            this.toolStripTextBoxSearch.ForeColor = Color.Black;
            this.toolStripTextBoxSearch.Font = regularFont;
        }

        private void toolStripTextBoxSearch_Leave(object sender, EventArgs e)
        {
            this.searchContent = this.toolStripTextBoxSearch.Text;
            if (string.IsNullOrEmpty(searchContent))
            {
                ShowSearchHint();
            }
        }

        private void ShowSearchHint()
        {
            this.toolStripTextBoxSearch.Font = ItalicFont;
            this.toolStripTextBoxSearch.Text = "Search";
            this.toolStripTextBoxSearch.ForeColor = SystemColors.Control;
        }

这里用this.searchContent保存实际存入的字符。运行一下看实际效果吧。

Advertisements
This entry was posted in 计算机与 Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s