幾個C#編程的小技巧 (一)
2024-07-21 02:18:33
供稿:網友
網站運營seo文章大全提供全面的站長運營經驗及seo技術!一、最小化窗口
點擊“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;
}