WinForm中的几个小技巧
屏蔽窗体右上角关闭按钮
一、重写OnClosing
protectedoverridevoid OnClosing(CancelEventArgs e)
{
if(this.Visible)
{
e.Cancel=true;
//
// WHATE TODO
//
}
}
二、重写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 单实例运行
/// <summary>
/// 单实例运行
/// </summary>
/// <param name="frm">所要运行的主窗体</param>
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);
/// <summary>
/// 将控件转为圆形
/// </summary>
/// <param name="control">控件名</param>
public static void MakeControlToCircle(Control[] control)
{
IntPtr dc;
IntPtr region;
for(int i=0;i<control.Length;i++)
{
dc=GetDC(control[i].Handle);
BeginPath(dc);
SetBkMode(dc,TRANSPARENT);
Ellipse(dc,0,0,control[i].Width-3,control[i].Height-2);
EndPath(dc);
region=PathToRegion(dc);
SetWindowRgn(control[i].Handle,region,false);
}
}
#endregion
在同一应用程序中同一窗体只打开一个
/// <summary>
/// 在同一应用程序中同一窗体只打开一个
/// </summary>
/// <param name="frmOpen">要打开的窗体实例</param>
/// <returns></returns>
public static void OpenSeamForm(Form frmOpen)
{
foreach (Form frm in Application.OpenForms)
{
if (frm.Text == frmOpen.Text)
{
frm.Visible = true;
frm.WindowState = FormWindowState.Normal;
frm.Activate();
return;
}
}
frmOpen.Show();
}