WinForm实现为TextBox设置水印文字 WinForm实现为TextBox设置水印文字功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

WinForm实现为TextBox设置水印文字 WinForm实现为TextBox设置水印文字功能

  2021-03-19 我要评论
想了解WinForm实现为TextBox设置水印文字功能的相关内容吗,在本文为您仔细讲解WinForm实现为TextBox设置水印文字的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:WinForm,TextBox,设置,水印文字,下面大家一起来学习吧。

本文实例展示了WinForm实现为TextBox设置水印文字功能,非常实用的技巧,分享给大家供大家参考。

关键代码如下:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WinFormUtilHelpV2
{
  /// <summary>
  /// 基于.NET 2.0的TextBox工具类
  /// </summary>
  public static class TextBoxToolV2
  {
    private const int EM_SETCUEBANNER = 0x1501;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]

    private static extern Int32 SendMessage
     (IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

    /// <summary>
    /// 为TextBox设置水印文字
    /// </summary>
    /// <param name="textBox">TextBox</param>
    /// <param name="watermark">水印文字</param>
    public static void SetWatermark(this TextBox textBox, string watermark)
    {
      SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, watermark);
    }
    /// <summary>
    /// 清除水印文字
    /// </summary>
    /// <param name="textBox">TextBox</param>
    public static void ClearWatermark(this TextBox textBox)
    {
      SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, string.Empty);
    }
  }
}

测试代码如下:

using System;
using System.Windows.Forms;
using WinFormUtilHelpV2;

namespace WinFormUtilHelpV2Test
{
  public partial class WinTextBoxToolV2Test : Form
  {
    public WinTextBoxToolV2Test()
    {
      InitializeComponent();
    }

    private void WinTextBoxToolV2Test_Load(object sender, EventArgs e)
    {
      textBox1.SetWatermark("请输入用户名称....");
      textBox2.SetWatermark("请输入用户密码....");
    }

    private void button1_Click(object sender, EventArgs e)
    {
      textBox1.ClearWatermark();
      textBox2.ClearWatermark();
    }
  }
}

测试效果如下图所示:

希望本文所述的为TextBox设置水印文字功能示例对大家C#程序设计有所帮助!

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们