2012年9月24日 星期一
c# Dialog全介紹
Author: Mango
|
at:凌晨3:06
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
Dialog全介紹
轉貼自:http://www.ziliaonet.com/tech/softdev/CJ/200604/53029.html
對話方塊中我們常用了以下幾種:
1、檔對話方塊(FileDialog) 它又常用到兩個:
打開文件對話方塊(OpenFileDialog)
保存檔對話(SaveFileDialog)
2、字體對話方塊(FontDialog)
3、顏色對話方塊(ColorDialog)
4、列印預瀏對話方塊(PrintPreviewDialog)
5、頁面設置(PrintDialog)
6、列印對話方塊(PrintDialog)
還有更多,有時間的網友可以看看MSDN。下面我們一個個來介紹。在介紹的過程中我用到了一個自己開發的類:File,主要是檔操作的。
文件對話方塊(FileDialog)
一、打開文件對話方塊(OpenFileDialog)
1、 OpenFileDialog控制項有以下基本屬性
InitialDirectory 對話方塊的初始目錄
Filter 要在對話方塊中顯示的檔篩選器,例如,"文字檔(*.txt)|*.txt|所有檔(*.*)||*.*"
FilterIndex 在對話方塊中選擇的檔篩選器的索引,如果選第一項就設為1
RestoreDirectory 控制對話方塊在關閉之前是否恢復目前的目錄
FileName 第一個在對話方塊中顯示的檔或最後一個選取的檔
Title 將顯示在對話方塊標題列中的字元
AddExtension 是否自動添加默認副檔名
CheckPathExists
在對話方塊返回之前,檢查指定路徑是否存在
DefaultExt 默認副檔名
DereferenceLinks 在從對話方塊返回前是否取消引用快捷方式
ShowHelp
啟用"幫助"按鈕
ValiDateNames 控制對話方塊檢查檔案名中是否不含有無效的字元或序列
2、 OpenFileDialog控制項有以下常用事件
FileOk 當用戶點擊"打開"或"保存"按鈕時要處理的事件
HelpRequest 當使用者點擊"?明"按鈕時要處理的事件
可以用以下代碼來實現上面這個對話方塊:
private void openFileDialogBTN_Click(object sender, System.EventArgs e){
OpenFileDialog openFileDialog=new OpenFileDialog();
openFileDialog.InitialDirectory="c:\\";//注意這裡寫路徑時要用c:\\而不是c:\
openFileDialog.Filter="文字檔|*.*|C#文件|*.cs|所有檔|*.*";
openFileDialog.RestoreDirectory=true;
openFileDialog.FilterIndex=1;
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
fName=openFileDialog.FileName;
File fileOpen=new File(fName);
isFileHaveName=true;
richTextBox1.Text=fileOpen.ReadFile();
richTextBox1.AppendText("");
}
}
其中有用到了File()這個類,是我在程式用來執行檔操作,自己寫的,在最後附了這個類的源碼。有興趣的網友可以自己分析。
二、保存檔對話方塊(SaveFileDialog)
保存檔對話方塊控制項有兩種情況,一就是保存,二就是另存為,保存很簡單,就是在檔已經打開的情況下的,再把檔寫一篇,在這裡我們主要講另存為的情況(SaveAs)。
1,SaveFileDialog控制項的屬性
Filter 要在對話方塊中顯示的檔篩選器,例如,"文字檔(*.txt)|*.txt|所有檔(*.*)|*.*"
FilterIndex 在對話方塊中選擇的檔篩選器的索引,如果選第一項就設為1
RestoreDirectory 控制對話方塊在關閉之前是否恢復目前的目錄
AddExtension 是否自動添加默認副檔名
CheckFileExists
CheckPathExists
在對話方塊返回之前,檢查指定路徑是否存在
Container 控制在將要創建檔時,是否提示用戶。只有在ValidateNames為真值時,才適用。
DefaultExt 缺省副檔名
DereferenceLinks
在從對話方塊返回前是否取消引用快捷方式
FileName 第一個在對話方塊中顯示的檔或最後一個選取的檔
InitialDirector 對話方塊的初始目錄
OverwritePrompt 控制在將要在改寫現在檔時是否提示用戶,只有在ValidateNames為真值時,才適用
ShowHelp 啟用"?明"按鈕
Title 將顯示在對話方塊標題列中的字元
ValidateNames 控制對話方塊檢查檔案名中是否不含有無效的字元或序列
2、SaveFileDialog事件如下:
FileOk 當用戶點擊"打開"或"保存"按鈕時要處理的事件
HelpRequest 當使用者點擊"?明"按鈕時要處理的事件
用下例代碼可以實現
private void saveAsDialogBTN_Click(object sender, System.EventArgs e)
{
SaveFileDialog saveFileDialog=new SaveFileDialog();
saveFileDialog.Filter="文字檔|*.*|C#文件|*.cs|所有檔|*.*";
saveFileDialog.FilterIndex=2;
saveFileDialog.RestoreDirectory=true;
if(saveFileDialog.ShowDialog()==DialogResult.OK)
{
if(saveFileDialog.ShowDialog()==DialogResult.OK)
{
fName=saveFileDialog.FileName;
File fSaveAs=new File(fName);
isFileHaveName=true; file://保存的檔有名字
fSaveAs.WriteFile(richTextBox1.Text);
}
}
}
其實這些都可以在VS.NET的IDE環境中直接完成,為了說明問題,我還是一條條列也來了。當中用到了一個File的類庫,下面是來源程式:
File.cs
using System;
using System.IO;
using System.Windows.Forms;
using System.Text;
namespace dialog
{
///
/// Summary description for File.
///
public class File
{
string fileName;
public File(string fileName)
{
this.fileName=fileName;
}
public string ReadFile()
{
try
{
StreamReader sr=new StreamReader(fileName,Encoding.Default);
string result=sr.ReadToEnd();
sr.Close();
return result;
}
catch(Exception e){MessageBox.Show(e.Message);}
return null;
}
public void WriteFile(string str)
{
try
{
StreamWriter sw=new StreamWriter(fileName,false,Encoding.Default);
sw.Write(str);
sw.Close();
}
catch(Exception e){MessageBox.Show(e.Message,"保存檔出錯!");}
}
}
}
字體對話方塊(FontDialog)
在文字處理中,我們常用到字體,現在我們來做一個最常見的字體對話方塊。
一、 字體對話方塊(FontDialog)常用屬性
ShowColor 控制是否顯示顏色選項
AllowScriptChange 是否顯示字體的字元集
Font 在對話方塊顯示的字體
AllowVerticalFonts 是否可選擇垂直字體
Color 在對話方塊中選擇的顏色
FontMustExist 當字體不存在時是否顯示錯誤
MaxSize 可選擇的最大字型大小
MinSize 可選擇的最小字型大小
ScriptsOnly 顯示排除OEM和Symbol字體
ShowApply 是否顯示"應用"按鈕
ShowEffects 是否顯示底線、刪除線、字體顏色選項
ShowHelp 是否顯示"幫助"按鈕
二、 字體對話方塊(FontDialog)的事件
Apply 當點擊"應用"按鈕時要處理的事件
HelpRequest 當點擊"幫助"按鈕時要處理的事件
實現代碼
private void fontDialogBTN_Click(object sender, System.EventArgs e)
{
FontDialog fontDialog=new FontDialog();
fontDialog.Color=richTextBox1.ForeColor;
fontDialog.AllowScriptChange=true;
fontDialog.ShowColor=true;
if(fontDialog.ShowDialog()!=DialogResult.Cancel)
{
richTextBox1.SelectionFont=fontDialog.Font;//將當前選定的文字改變字體
}
}
上面代碼將選定的文本設置為當前FontDialog對話方塊中的字體。
顏色對話方塊(ColorDialog)
顏色拾取框也是我們常見的對話方塊之一,下面我們來看看在C#中是如何操作顏色對話方塊的呢?
一、 顏色對話方塊(ColorDialog)的常見屬性
AllowFullOpen 禁止和啟用"自訂顏色"按鈕
FullOpen 是否最先顯示對話方塊的"自訂顏色"部份
ShowHelp 是否顯示"?明"按鈕
Color 在對話方塊中顯示的顏色
AnyColor 顯示可選擇任何顏色
CustomColors 是否顯示自訂顏色
SolidColorOnly 是否只能選擇純色
實現代碼見下:
private void colorDialogBTN_Click(object sender, System.EventArgs e)
{
ColorDialog colorDialog=new ColorDialog();
colorDialog.AllowFullOpen=true;
colorDialog.FullOpen=true;
colorDialog.ShowHelp=true;
colorDialog.Color=Color.Black;//初始化當前文字方塊中的字體顏色,當使用者在ColorDialog對話方塊中點擊"取消"按鈕
file://恢復原來的值
colorDialog.ShowDialog();
richTextBox1.SelectionColor=colorDialog.Color;
}
實現顏色對話方塊(ColorDialog)很容易吧,其實不只是顏色對話方塊,C#也是很容易的,只要用心去學,都容易的。講完了顏色對話方塊(ColorDialog),我們來講列印和頁面設置.
頁面設置(PageSetupDialog)
其實頁面設置(PageSetupDialog)沒有太多的講,既然講到這裡,我還是把PageSetupDialog中常用的屬性列出來吧
一、頁面設置(PageSetupDialog)常見屬性
AllowMargins 設置是否可以對邊距的編輯
AllowOrientation 是否可以使用"方向"單選框
AllowPaper 設置是否可以對紙張大小的編輯
AllowPrinter 設置是否可以使用"印表機"按鈕
Document 獲取印表機設置的PrintDocument
MinMargins 允許用戶選擇的最小邊距
就這麼簡單啦,我們看看下面的吧,還有更重磅的東東呢?關於列印的。
列印預瀏及列印
列印是我們在windows程式設計中常要用到的功能,在以前都是很麻煩工作,但在Microsoft .net Framework中列印是以元件提供給我們使用,不過還是點麻煩的,所以就專門寫出來,供大家參改。
一, 在.net環境中,說到列印,就不能不說PrintDocumet這個類,PrintDocument屬於System.Drawing.Printing這個名字空間,PrintDocument這個類是實現列印的核心代碼。
如果要實現列印,就必需首先構造PrintDocument物件添加列印事件,
printDocument.PrintPage+=new PrintPageEventHandler(this.printDocument_PrintPage)
列印其實也是調用Graphics類的方法進行畫圖,下面這代碼是根據MSDN上提供的常式改寫的。MSDN列印常式位址:
microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDrawingPrintingPrintDocumentClassTopic.asp>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDrawingPrintingPrintDocumentClassTopic.asp ,有興趣的網友可以參改一下。
下面是我改寫的printDocument_PrintPage:
private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
float linesPerPage=0;//頁面的行號
float yPos=0;//列印字串的縱向位置
int count=0;//行計數器
float leftMargin =e.MarginBounds.Left;//左邊距
float topMargin=e.MarginBounds.Top;//上邊距
string line=null;//行字串
Color clr=richTextBox1.SelectionColor;//當前的列印顏色,在我這個程式沒有實現不同顏色列印
SolidBrush b =new SolidBrush(clr);//刷子
fnt=richTextBox1.SelectionFont;//當前的列印字體
linesPerPage=e.MarginBounds.Height/fnt.GetHeight(e.Graphics);//每頁可列印的行數
file://逐行循行列印一頁
while(count
{
yPos=topMargin+(count*fnt.GetHeight(e.Graphics));
e.Graphics.DrawString(line,fnt,b,leftMargin,yPos,new StringFormat());
count++;
}
file://如果該頁列印完成而line不為空說明還有沒完成的頁面,發出下一次的列印事件,
file://在下一次的列印中lineReader會自動讀取上次沒有列印完的內容。lineReader可以記錄當前讀取的位置
if(line!=null)
e.HasMorePages=true;
else
e.HasMorePages=false;
}
在這裡可以完成整個列印任務。把printDocument_PrintPage構造好後,就可以列印和列印預瀏。
二、列印預瀏對話方塊(PrintPreviewDialog)
列印預瀏控制項是用來顯示一個列印文檔在列印後的效果。在列印預瀏對話方塊中包含有,列印、縮放、單頁或多頁、關閉等按鈕。對話方塊如下:
列印預瀏對話方塊沒有太多的屬性,最後通過ShowDialog()調用。上面的實現代碼如下:
private void printPreviewBTN_Click(object sender, System.EventArgs e)
{
lineReader = new StringReader(richTextBox1.Text);
try
{
PrintPreviewDialog printPreviewDialog1=new PrintPreviewDialog();
printPreviewDialog1.Document=printDocument;
printPreviewDialog1.FormBorderStyle=FormBorderStyle.Fixed3D;
printPreviewDialog1.ShowDialog(this);
}
catch(Exception excep)
{
MessageBox.Show(excep.Message, "列印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
很簡單的,只要你把PrintDocument_PrintPage()寫好了,這裡就很容易了。
三、列印對話方塊(PrintDialog)
1、列印對話方塊(PrintDialog)只要有以下屬性:
AllowPrintToFile 禁止或使用"列印到檔"核取方塊
AllowSelection 禁止或使用"選定內容"單選框
AllowSomePages 禁止或使用"頁"選項按鈕
Document 從中獲取印表機設置的PrintDocument
PrintToFile 列印到檔"核取方塊是否選中
ShowHelp 控制是否顯示"?明"按鈕
ShowNetWork 控制是否顯示"網路"按鈕
用如下代碼來實現:
private void printDialogBTN_Click(object sender, System.EventArgs e)
{
PrintDialog printDialog=new PrintDialog();
printDialog.Document=printDocument;
if(printDialog.ShowDialog()!=DialogResult.Cancel)
{
try
{
printDocument.Print();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
到此,所有的對話方塊都講完了,頭都大了吧。
上述對話方塊,完全可以在vs.net的IDE環境中完成 ,這時為了說明問題,才分開一步步來講。
總結
在我們的教程,共講述了檔對話方塊(FileDialog)、字體對話方塊(FontDialog)、,顏色對話方塊(ColorDialog)、列印預瀏對話方塊(PrintPreviewDialog)、頁面設置(PrintDialog)、列印對話方塊(PrintDialog),這幾個對話方塊,其中檔對話方塊(FileDialog)又有:打開檔對話方塊(OpenFileDialog)、保存檔對話(SaveFileDialog)這兩個對話方塊。有了上述基礎,大家可以很容易的寫出一個簡單的記事本。
將顏色16進位字串色碼轉成 System.Drawing.Color 物件
Author: Mango
|
at:凌晨3:04
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
將 #FF1000 轉成color
和反轉成 #色碼
//色碼轉換 16進制轉10進制
public static Color HexColor(String hex)
{
//將井字號移除
hex = hex.Replace("#", "");
byte a = 255;
byte r = 255;
byte g = 255;
byte b = 255;
int start = 0;
//處理ARGB字串
if (hex.Length == 8)
{
a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
start = 2;
}
else if (hex.Length < 6) //錯誤的色碼 直接輸出預設值#000000
{
return Color.FromArgb(255, 17, 0, 0);
}
// 將RGB文字轉成byte
r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);
return Color.FromArgb(a, r, g, b);
}
//反色碼轉換 Color的10進制轉16進制
public static String XColor(Color _co)
{
//處理ARGB字串
string _a = _co.A.ToString("X").PadLeft(2, '0');
string _r = _co.R.ToString("X").PadLeft(2, '0');
string _g = _co.G.ToString("X").PadLeft(2, '0');
string _b = _co.B.ToString("X").PadLeft(2, '0');
return "#" + _r + _g + _b;
}
參考
http://www.cnblogs.com/wxbjs/archive/2010/07/15/1777916.html
http://www.dotblogs.com.tw/junegoat/archive/2012/06/22/color-convert-form-hex-string.aspx
2012年8月27日 星期一
C# FormBorderStyle.None 改變窗體大小的UI
Author: Mango
|
at:凌晨1:39
|
Category :
.NET,
C#,
visual studio 2008
|
當表單的FormBorderStyle 被設定成 System.Windows.Forms.FormBorderStyle.None
也就是 無邊框模式 又想有 改變form大小的UI時
加入下面這段就行了
const int WM_NCHITTEST = 0x0084;
const int HTLEFT = 10;
const int HTRIGHT = 11;
const int HTTOP = 12;
const int HTTOPLEFT = 13;
const int HTTOPRIGHT = 14;
const int HTBOTTOM = 15;
const int HTBOTTOMLEFT = 0x10;
const int HTBOTTOMRIGHT = 17;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
Point vPoint = new Point((int)m.LParam & 0xFFFF,
(int)m.LParam >> 16 & 0xFFFF);
vPoint = PointToClient(vPoint);
if (vPoint.X <= 5)
if (vPoint.Y <= 5)
m.Result = (IntPtr)HTTOPLEFT;
else if (vPoint.Y >= ClientSize.Height - 5)
m.Result = (IntPtr)HTBOTTOMLEFT;
else m.Result = (IntPtr)HTLEFT;
else if (vPoint.X >= ClientSize.Width - 5)
if (vPoint.Y <= 5)
m.Result = (IntPtr)HTTOPRIGHT;
else if (vPoint.Y >= ClientSize.Height - 5)
m.Result = (IntPtr)HTBOTTOMRIGHT;
else m.Result = (IntPtr)HTRIGHT;
else if (vPoint.Y <= 5)
m.Result = (IntPtr)HTTOP;
else if (vPoint.Y >= ClientSize.Height - 5)
m.Result = (IntPtr)HTBOTTOM;
break;
}
}
2012年8月7日 星期二
C# 獲取當前路徑的方法集合
Author: Mango
|
at:凌晨12:44
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
/ /獲取當前進程的完整路徑,弱者受制與文件名(進程名)。
字符串str= this.GetType()Assembly.Location;
結果:X:\ XXX\ XXX\ xxx.exe(。EXE文件所在的目錄+ EXE文件名)
/ /獲取新的過程
字符串str= System.Diagnostics.Process.GetCurrentProcess()MainModule.FileName;
結果:X:\ XXX\ XXX\ xxx.exe(。EXE文件所在的目錄+ EXE文件名)
/ /獲取和設定當前目錄(即該進程從中啟動的目錄)的完全限定路徑。
字符串str System.Environment.CurrentDirectory;
結果:為X:\ XXX\ XXX(EXE文件所在的目錄)
/ /獲取當前線索的當前應用程序,要求該船撒的-base目錄,它由程序,集衝突解決程序,用來探測程序,集。
字符串str System.AppDomain.CurrentDomain.BaseDirectory;
結果:為X:\ XXX\ XXX\(。EXE文件所在的目錄“\”)
/ /獲取和設定弱者受制與該應用程序,的目錄的名稱。
字符串str System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
結果:為X:\ XXX\ XXX\(。EXE文件所在的目錄“\”)
/ /獲取啟動了應用程序,的可執行文件的路徑,不包括可執行文件的名稱。
字符串str System.Windows.Forms.Application.StartupPath;
結果:為X:\ XXX\ XXX(EXE文件所在的目錄)
/ /獲取啟動了應用程序,的可執行文件的路徑,包括可執行文件的名稱。
字符串str System.Windows.Forms.Application.ExecutablePath;
結果:X:\ XXX\ XXX\ xxx.exe(。EXE文件所在的目錄+ EXE文件名)
/ /獲取應用程序,的當前工作目錄(不可靠)。
字符串str= System.IO.Directory.GetCurrentDirectory();
結果:為X:\ XXX\ XXX(EXE文件所在的目錄)
2012年7月11日 星期三
C# get和set關鍵字 範例
Author: Mango
|
at:晚上11:53
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
將變數 tran 設定在 -360 ~ 360
private float _tran; //此為private,外界無法看到該屬性
public float tran //public 外界可存取
{
get
{
return _tran;
}
set
{
if (value <= -360 || value > 360)
value = 1; //set要用到value這個關鍵字,value就是要寫入的值
_tran = value;
}
}
2012年6月18日 星期一
C# ref/out 關鍵字 筆記
Author: Mango
|
at:凌晨4:26
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
ref是傳遞參數的地址,out是返回值,兩者有一定的相同之處,不過也有不同點。
使用ref前必須對變量賦值,out不用。
out的函數會清空變量,即使變量已經賦值也不行,退出函數時所有out引用的變量都要賦值,ref引用的可以修改,也可以不修改。
以下摘錄自 MSDN Library:
以 ref 參數傳遞的引數必須先被初始化,out 則不需要。
out 參數要在離開目前的方法之前至少有一次指派值的動作。
若兩個方法僅有 ref、out 關鍵字的差異,在編譯期會視為相同方法簽章,無法定義為多載方法。
private void Form1_Load(object sender, EventArgs e)
{
string name = "jan";
Console.WriteLine("原 " + name);
Console.WriteLine("改 " + fun1(ref name));
Console.WriteLine("原 " + name);
Console.WriteLine();
Console.WriteLine("改 " + fun2(out name));
Console.WriteLine("原 " + name);
}//
string fun2(out string _st)
{
_st = "";
_st += "pan";
return _st;
}
string fun1(ref string _st)
{
_st += "pan";
return _st;
}
string fun1(string _st)
{
_st += "pan";
return _st;
}
2012年5月31日 星期四
C# DateTime 日期 時間 格式 計算
Author: Mango
|
at:凌晨1:55
|
Category :
C#,
visual studio 2008
|
轉自 http://giga0066.pixnet.net/blog/post/29817017-c%23-datetime-format-%E6%97%A5%E6%9C%9F-%E6%99%82%E9%96%93-%E6%A0%BC%E5%BC%8F
DateTime.Now.ToShortTimeString()
DateTime dt = DateTime.Now;
dt.ToString();//2005-11-5 13:21:25
dt.ToFileTime().ToString();//127756416859912816
dt.ToFileTimeUtc().ToString();//127756704859912816
dt.ToLocalTime().ToString();//2005-11-5 21:21:25
dt.ToLongDateString().ToString();//2005年11月5日
dt.ToLongTimeString().ToString();//13:21:25
dt.ToOADate().ToString();//38661.5565508218
dt.ToShortDateString().ToString();//2005-11-5
dt.ToShortTimeString().ToString();//13:21
dt.ToUniversalTime().ToString();//2005-11-5 5:21:25
dt.Year.ToString();//2005
dt.Date.ToString();//2005-11-5 0:00:00
dt.DayOfWeek.ToString();//Saturday
dt.DayOfYear.ToString();//309
dt.Hour.ToString();//13
dt.Millisecond.ToString();//441
dt.Minute.ToString();//30
dt.Month.ToString();//11
dt.Second.ToString();//28
dt.Ticks.ToString();//632667942284412864
dt.TimeOfDay.ToString();//13:30:28.4412864
dt.ToString();//2005-11-5 13:47:04
dt.AddYears(1).ToString();//2006-11-5 13:47:04
dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
dt.AddMonths(1).ToString();//2005-12-5 13:47:04
dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
dt.CompareTo(dt).ToString();//0
dt.Add(?).ToString();//問號為一個時間段
dt.Equals("2005-11-6 16:11:04").ToString();//False
dt.Equals(dt).ToString();//True
dt.GetHashCode().ToString();//1474088234
dt.GetType().ToString();//System.DateTime
dt.GetTypeCode().ToString();//DateTime
dt.GetDateTimeFormats(s)[0].ToString();//2005-11-05T14:06:25
dt.GetDateTimeFormats(t)[0].ToString();//14:06
dt.GetDateTimeFormats(y)[0].ToString();//2005年11月
dt.GetDateTimeFormats(D)[0].ToString();//2005年11月5日
dt.GetDateTimeFormats(D)[1].ToString();//2005 11 05
dt.GetDateTimeFormats(D)[2].ToString();//星期六 2005 11 05
dt.GetDateTimeFormats(D)[3].ToString();//星期六 2005年11月5日
dt.GetDateTimeFormats(M)[0].ToString();//11月5日
dt.GetDateTimeFormats(f)[0].ToString();//2005年11月5日 14:06
dt.GetDateTimeFormats(g)[0].ToString();//2005-11-5 14:06
dt.GetDateTimeFormats(r)[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT
string.Format("{0:d}",dt);//2005-11-5
string.Format("{0:D}",dt);//2005年11月5日
string.Format("{0:f}",dt);//2005年11月5日 14:23
string.Format("{0:F}",dt);//2005年11月5日 14:23:23
string.Format("{0:g}",dt);//2005-11-5 14:23
string.Format("{0:G}",dt);//2005-11-5 14:23:23
string.Format("{0:M}",dt);//11月5日
string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
string.Format("{0:s}",dt);//2005-11-05T14:23:23
string.Format("{0:t}",dt);//14:23
string.Format("{0:T}",dt);//14:23:23
string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
string.Format("{0:U}",dt);//2005年11月5日 6:23:23
string.Format("{0:Y}",dt);//2005年11月
string.Format("{0}",dt);//2005-11-5 14:23:23
string.Format("{0:yyyyMMddHHmmssffff}",dt);
計算2個日期之間的天數差
-----------------------------------------------
DateTime dt1 = Convert.DateTime("2007-8-1");
DateTime dt2 = Convert.DateTime("2007-8-15");
TimeSpan span = dt2.Subtract(dt1);
int dayDiff = span.Days + 1;
計算某年某月的天數
-----------------------------------------------
int days = DateTime.DaysInMonth(2007, 8);
days = 31;
給日期增加一天、減少一天
-----------------------------------------------
DateTime dt =DateTime.Now;
dt.AddDays(1); //增加一天
dt.AddDays(-1);//減少一天
其它年份方法類似...
Oracle SQL裡轉換日期函數
-----------------------------------------------
to_date("2007-6-6",YYYY-MM-DD");
to_date("2007/6/6",yyyy/mm/dd");
如下一組數據,如何查找表裡包含9月份的記錄:
CGGC_STRATDATE CGGC_ENDDATE
=========================================
2007-8-4 2007-9-5
2007-9-5 2007-9-20
2007-9-22 2007-10-5
SELECT * FROM TABLE
(TO_DATE(2007/9/1,yyyy/mm/dd) BETWEEN CGGC_STRATDATE
AND CGGC_ENDDATE OR CGGC_STRATDATE >=TO_DATE(2007/9/1,yyyy/mm/dd)
AND CGGC_ENDDATE<=TO_DATE(2007/9/30,yyyy/mm/dd) "
OR TO_DATE(2007/9/30,yyyy/mm/dd) BETWEEN CGGC_STRATDATE
AND CGGC_ENDDATE) ORDER BY CGGC_STRATDATE ASC
========================================
轉自http://www.dotblogs.com.tw/darren.net/archive/2009/02/26/7303.aspx
時間相減
DateTime dt1 = new DateTime(2008, 12, 31);
DateTime dt2 = DateTime.Now;
TimeSpan ts =dt2 - dt1;
//相差天數(未滿一天捨去,return int type)
Response.Write(Convert.ToString( ts.Days ));
//相差天數(未滿一天亦計入,return double type)
Response.Write(Convert.ToString( ts.TotalDays ));
//相差小時數(return double type)
Response.Write(Convert.ToString( ts.TotalHours ));
//相差秒數(return double type)
Response.Write(Convert.ToString( ts.TotalMinutes ));
2012年2月28日 星期二
[C#] 服務器提交協議衝突Section=ResponseStatusLine 的解決辦法
Author: Mango
|
at:清晨6:22
|
Category :
.NET,
C#,
Framework 3.5,
visual studio 2008
|
轉自http://blog.csdn.net/liehuo123/article/details/5689222
最近在用.net寫一個網絡蜘蛛,發現對有的網站用HttpWebrequest抓取網頁的時候會報錯,捕獲異常提示:"服務器提交了協議衝突Section=ResponseStatusLine ”,改用WebClient也是同樣問題,後來知道,WebClient是對HttpWebrequest進一步進行了封裝。
最後終於找到問題根源:The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF微軟沒有容忍不符合RFC 822中的httpHeader必須以CRLF結束的規定的服務器響應。
通過修改配置文件解決:在app.config(WinForm)或web.config(Web)文件裡修改。WinForm下的app.config文件中添加:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
完整app.config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system. net>
</configuration>
2012年1月11日 星期三
[C#]讓Webbrowser中的js直接呼叫Winform的function
Author: Mango
|
at:凌晨3:51
|
Category :
C#,
visual studio 2008
|
引用: http://www.dotblogs.com.tw/jimmyyu/archive/2009/09/24/10758.aspx
在js 裡面用 window.external 來呼叫winform的function
其他參考
http://www.iteye.com/topic/243494
========================================================
简介:window.external.AddFavorite这个把网站添加到浏览者收藏夹的脚本大家应该常常看过,但你还知道window.external的另外一些用法呢?由于是一些关于系统文件操作的命令,因为安全设置有些脚本会出错误.
1.external.AddDesktopComponent 把网站作为用户的Active桌面
语法:external.AddDesktopComponent(地址,类型[image/website],左距离,顶距离,宽度,长度)
- function j_adc(){ //例子
- window.external.AddDesktopComponent("http://...","website",0,0,800,600);
- }
2.external.AddFavorite 把网站加入到用户的收藏夹
语法:external.AddFavorite(网址,标题);
- function j_af(){
- window.external.AddFavorite(location.href, document.title);
- }
3.external.NavigateAndFind 搜索指定网站中的某个字段
语法:external.NavigateAndFind(文件地址,关键字,_Target)
- function j_an(){
- window.external.NavigateAndFind("http://...",gosearch.value,"");
- }
4.external.ShowBrowserUI 调用语言选择窗口与收藏夹管理窗口
语法:external.ShowBrowserUI(类型[LanguageDialog/OrganizeFavorites], null)
- <input type="button" name="Button" value="语言设置" onclick="window.external.ShowBrowserUI('LanguageDialog', null)">
- <input type="button" name="Submit2" value="整理收藏夹" onclick="window.external.ShowBrowserUI('OrganizeFavorites', null)">
5.external.ImportExportFavorites 导入与导出用户收藏夹
语法:external.ImportExportFavorites(导入/true 导出/false, 文件路径)
- <input type="button" name="Button" value="导入收藏夹" onClick=window.external.ImportExportFavorites(true,"http://...");>
- <input type="button" name="Button3" value="导出收藏夹" onClick=window.external.ImportExportFavorites(false,"http://...");>
6.external.addChanne 加入到频道
语法:external.addChannel(网页路径)
7.下面是external对象所有方法列表
| Method | Description |
|---|---|
| AddChannel | Obsolete. Presents a dialog box that enables the user to add the specified channel, or to change the channel URL, if it is already installed. |
| AddDesktopComponent | Adds a Web site or image to the Microsoft Active Desktop. |
| AddFavorite | Prompts the user with a dialog box to add the specified URL to theFavorites list. |
| AddSearchProvider | Adds a search provider to the registry. |
AddService ![]() | User initiated action to add a service. |
AddToFavoritesBar ![]() | Adds a URL to the Favorites Bar. |
| AutoCompleteSaveForm | Saves the specified form in the AutoComplete data store. |
| AutoScan | No longer available as of Internet Explorer 7. Attempts to connect to a Web server by passing the specified query through completion templates. |
| BrandImageUri | Not supported. Retrieves the Uniform Resource Identifier (URI) of an alternate product image. |
| bubbleEvent | Propagates an event up its containment hierarchy. |
ContentDiscoveryReset ![]() | Resets the list of feeds, search providers, and Web Slices associated with the page. |
| CustomizeClearType | Not supported. Sets a registry value to turn ClearType on or off. |
| CustomizeSettings | Not supported. Saves the user settings from a "first run" page. |
| DefaultSearchProvider | Not supported. Retrieves the name of the user's default search provider. |
| DiagnoseConnection | Not supported. Attempts to diagnose problems with the network connection. |
| ImportExportFavorites | Deprecated. Handles the import and export of Internet Explorer favorites. |
InPrivateFilteringEnabled ![]() | Detects whether the user has enabled InPrivate Filtering. |
| IsSearchMigrated | Not supported. Determines whether autosearch settings were migrated from a previous version of Internet Explorer. |
| IsSearchProviderInstalled | Determines if a search provider has been installed for the current user and whether it is set as default. |
IsServiceInstalled ![]() | Check if a service is already installed. |
| IsSubscribed | Obsolete. Retrieves a value indicating whether the client subscribes to the given channel. |
| NavigateAndFind | Navigates to the specified URL and selects the specified text. |
| PhishingEnabled | Not supported. Determines whether Microsoft Phishing Filter is enabled. |
| raiseEvent | Triggers an event, as specified. |
| RunOnceHasShown | Not supported. Determines whether the "first run" page has been shown. |
| RunOnceRequiredSettingsComplete | Not supported. Sets a registry value to indicate whether the "first run" page completed successfully. |
| RunOnceShown | Not supported. Sets a registry value to indicate that the "first run" page has been shown. |
| SearchGuideUrl | Not supported. Retrieves the URL of a page that can be used to install additional search providers. |
| setContextMenu | Constructs a context menu, as specified. |
| ShowBrowserUI | Opens the specified browser dialog box. |
| SkipRunOnce | Not supported. Enables the user to select "first run" settings at a later time. |
| SkipTabsWelcome | Not supported. Disables the welcome screen that appears when opening a new tab in Internet Explorer 7. |
| SqmEnabled | Not supported. Determines whether Software Quality Monitoring (SQM) is enabled. |
参考:http://msdn.microsoft.com/en-us/library/ms535246%28VS.85%29.aspx
訂閱:
文章 (Atom)
.gif)

