欢迎光临
我们一直在努力

几个C#编程的小技巧 (一)-.NET教程,C#语言

建站超值云服务器,限时71元/月

一、最小化窗口

点击“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;

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 几个C#编程的小技巧 (一)-.NET教程,C#语言
分享到: 更多 (0)