几个C#编程的小技巧 (一)

王朝c#·作者佚名  2006-12-16
窄屏简体版  字體: |||超大  

一、最小化窗口

点击“X”或“Alt+F4”时,最小化窗口,

如:

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);

}

二、如何让Foreach 循环运行的更快

foreach是一个对集合中的元素进行简单的枚举及处理的现成语句,用法如下例所示:

using System;

using System.Collections;

namespace LoopTest

{

class Class1

{

static void Main(string[] args)

{

// create an ArrayList of strings

ArrayList array = new ArrayList();

array.Add("Marty");

array.Add("Bill");

array.Add("George");

// print the value of every item

foreach (string item in array)

{

Console.WriteLine(item);

}

}

}

你可以将foreach语句用在每个实现了Ienumerable接口的集合里。如果想了解更多foreach的用法,你可以查看.NET Framework SDK文档中的C# Language Specification。

在编译的时候,C#编辑器会对每一个foreach 区域进行转换。IEnumerator enumerator = array.GetEnumerator();

try

{

string item;

while (enumerator.MoveNext())

{

item = (string) enumerator.Current;

Console.WriteLine(item);

}

}

finally

{

IDisposable d = enumerator as IDisposable;

if (d != null) d.Dispose();

}

这说明在后台,foreach的管理会给你的程序带来一些增加系统开销的额外代码。

三、将图片保存到一个XML文件

WinForm的资源文件中,将PictureBox的Image属性等非文字内容都转变成文本保存,这是通过序列化(Serialization)实现的,

例子://

using System.Runtime.Serialization.Formatters.Soap;

Stream stream = new FileStream("E:\\Image.xml",FileMode.Create,FileAccess.Write,FileShare.None);

SoapFormatter f = new SoapFormatter();

Image img = Image.FromFile("E:\\Image.bmp");

f.Serialize(stream,img);

stream.Close();

四、屏蔽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;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航