WinForm中的几个实用技巧汇总
来源: 互联网 发布时间:2014-11-02
本文导语: 本文汇总了几个WinForm中常见的实用技巧,对于C#程序开发有着很好的参考借鉴价值。具体分析如下: 一、屏蔽窗体右上角关闭按钮 1.重写OnClosing protected override void OnClosing(CancelEventArgs e) { if(this.Visible) { e.Cancel=true; ...
本文汇总了几个WinForm中常见的实用技巧,对于C#程序开发有着很好的参考借鉴价值。具体分析如下:
一、屏蔽窗体右上角关闭按钮
1.重写OnClosing
protected override void OnClosing(CancelEventArgs e)
{
if(this.Visible)
{
e.Cancel=true;
//
// WHATE TODO
//
}
}
2.重写WndProc
protected override void WndProc(ref Message m)
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_CLOSE = 0xF060;
if (m.Msg == WM_SYSCOMMAND && (int) m.WParam == SC_CLOSE)
{
// User clicked close button
this.WindowState = FormWindowState.Minimized;
return;
}
base.WndProc(ref m);
}
更多方法可以参考:
http://topic.csdn.net/u/20091220/21/5228d0d6-26aa-48b8-81aa-293f7c7339f8.html?94449
http://topic.csdn.net/u/20090419/18/970d8ad9-ed9a-4bd9-a623-81d23106545b.html
二、屏蔽CTRL-V
在WinForm中的TextBox控件没有办法屏蔽CTRL-V的剪贴板粘贴动作,如果需要一个输入框,但是不希望用户粘贴剪贴板的内容,可以改用RichTextBox控件,并且在KeyDown中屏蔽掉CTRL-V键,例子:
private void richTextBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.Control && e.KeyCode==Keys.V)
e.Handled = true;
}
三、应用程序单例运行
#region 单实例运行
///
/// 单实例运行
///
/// 所要运行的主窗体
public static void SingleRun(Form frm)
{
System.Threading.Mutex mutex = new System.Threading.Mutex(false,"SINGLE_INSTANCE_MUTEX");
if (!mutex.WaitOne(0, false))
{
mutex.Close();
mutex = null;
}
if (mutex != null)
{
Application.Run(frm);
}
else
{
MessageBox.Show("应用程序已启动","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
#endregion
四、将控件转换成圆形
#region 将控件转换为圆形
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern IntPtr BeginPath(IntPtr hdc);
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern int SetBkMode(IntPtr hdc,int nBkMode);
const int TRANSPARENT=1;
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern IntPtr EndPath(IntPtr hdc);
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern IntPtr PathToRegion(IntPtr hdc);
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern int Ellipse(IntPtr hdc,int x1,int y1,int x2,int y2);
[System.Runtime.InteropServices.DllImport("user32")]
private static extern IntPtr SetWindowRgn(IntPtr hwnd,IntPtr hRgn,bool bRedraw);
[System.Runtime.InteropServices.DllImport("user32")]
private static extern IntPtr GetDC(IntPtr hwnd);
///
/// 将控件转为圆形
///
/// 控件名
public static void MakeControlToCircle(Control[] control)
{
IntPtr dc;
IntPtr region;
for(int i=0;i