首页 >> Asp.Net >> 正文
ASP.NET中的状态管理-ASP.NET
  来源:Dotnet频道 作者:采集 时间:2008-3-17  

  我们在ASP中能够通过cookie、查询字符串、应用程序、对话等轻易地解决这些问题。现在到了ASP.NET环境中,我们仍然可以使用这些功能,只是它们的种类更多了,功能也更强大了。
  
    管理互联网网页主要有二种不同的方法:客户端和服务器端。
  
  1、客户端的状态管理:
  
    在客户端、服务器之间的多次请求-应答期间,服务器上不保存信息,信息将被存储在网页或用户的计算机上。
  
    A、Cookie
  
    cookie是存储在客户端文件系统的文本文件中或客户端浏览器对话的内存中的少量数据,它主要用来跟踪数据设置。下面我们举例说明:假设我们要定制化一个欢迎互联网网页,当用户请求缺省的互联网网页时,应用程序会首先检查用户在此前是否已经注册,我们可以从cookie中获取用户的信息:
  
  [c#]
  if (Request.Cookies[“username”]!=null)
  lbMessage.text=”Dear “+Request.Cookies[“username”].Value+”, Welcome shopping here!”;
  else
  lbMessage.text=”Welcome shopping here!”;
  
    如果要存储用户的资料,我们可以使用下面的代码:
  
  [c#]
  Response.Cookies[“username’].Value=username;
  
     这样,当用户请求该网页时,我们就可以方便地识别该用户。
  
    B、隐藏域
  
    隐藏域不会显示在用户的浏览器中,但我们可以象设置标准控制的属性那样设置其属性。当一个网页被提交给服务器时,隐藏域的内容和其他控制的值一块儿被送到HTTP Form集合中。隐藏域可以是任何存储在网页中的与网页有关的信息的存储库,隐藏域在其value属性中存储一个变量,而且必须被显性地添加在网页上。
  
    ASP.NET中的HtmlInputHidden控制提供了隐藏域的功能。
  
  [c#]
  protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
  file://给隐藏域赋值
  Hidden1.Value=”this is a test”;
  file://获得一个隐藏域的值
  string str=Hidden1.Value;
  
    需要注意的是,要使用隐藏域,就必须使用HTTP-Post方法提交互联网网页。尽管其名字是隐藏域,但它的值并不是隐藏的,我们可以通过“查看源代码”功能找到它的值。

    C、状态查看
  
    包括网页本身在内的Web Forms网页上的每个控制都有一个名字为ViewState的属性,它是一个自动保持网页和控制状态的内置结构,这意味着在向服务器提交网页后,我们无需采取任何措施来恢复控制的数据。
  在这里,对我们有用的是ViewState属性,我们可以利用它来保存与服务器之间多次的请求-应答期间的信息。
  
  [c#]
  file://保存信息
  ViewState.Add(“shape”,”circle”);
  file://获取信息
  string shapes=ViewState[“shape”];
  
    注意:与隐藏域不同的是,在使用查看源代码功能时,ViewState属性的值是不可见的,它们是被压缩和加密的。

    D、查询字符串
  
    查询字符串提供了一种简单而受限制的维护状态信息的方法,我们可以方便地将信息从一个网页传递给另一个网页,但大多数浏览器和客户端装置都把URL的长度限制在255个字符长。此外,查询值是通过URL传递给互联网的,因此,在有些情况下,安全就成了一个大问题。
  
    带有查询字符串的URL如下所示:
  
     http://www.examples.com/list.aspx?categoryid=1&productid=101
  
    当有客户端请求list.aspx后,可以通过下面的代码获取目录和产品信息:
  
  [c#]
  string categoryid, productid;
  categoryid=Request.Params[“categoryid”];
  productid=Request.Params[“productid”];
  
    注意,我们只能使用HTTP-Get提交该互联网网页,否则就不能从查询字符串获得需要的值。

    2、服务器端的状态管理
  
    信息存储在服务器上,尽管其安全性较高,但会占用较多的web服务器资源。
  
    A、Aplication对象
  
    Aplication对象提供了一种让所有在Web应用服务器中运行的代码访问的存储数据的机制,插入应用程序对象状态变量的数据应该能够被多个对话共享,而且不会频繁地改变。正是因为它能够被全部应用程序所访问,因此,我们需要使用Lock和UnLock对避免其中的值出现冲突。
  
  
  [c#]
  Application.Lock();
  Application[“mydata”]=”mydata”;
  Application.UnLock(); 
   
 

 

[1] [2] [3] [4] [5] [6] [7] 下一页  

 

   B、Session对象
  
    Session对象可以用来存储需要在服务器的多次请求-应答期间和对网页的请求期间进行维护的指定对话的信息。Session对象是每个对话的存在的基础,也就是说不同的客户端生成不同的Session对象。存储在对话状态变量中的数据存在的周期较短。
  
    每个活动的ASP.NET对话是由一个包含合法的URL ASCII字符、长度为120位的SessionID字符串唯一确定和跟踪的。SessionID的值是由一个能够保证唯一性的算法生成的,以便对话之间不会冲突,SessionID的随意性使得我们很难猜测出一介现有对话的ID。
  
    根据应用程序的配置设置情况,SessionID通过HTTP cookie或修改后的URL在客户端-服务器请求之间进行传输。那么,如何设置应用程序配置的对话装备方法。
  
    每个web应用程序必须有一个名字为web.config的配置文件,它是基于XML文件的。下面是一个名字为sessionState的对话:
  
  
    cookieless选项的值为true或false。当其值为false(缺省值)时,ASP.NET将使用HTTP cookie来识别用户;当其值是true时,ASP.NET将随机地生成一个唯一的号码,并将它放在被请求的文件的前面,这一号码是用来识别用户的,我们能够在IE的地址栏中看到它:
  
    http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx
    OK,下面我们再回到session对象。
  
  [c#]
  file://存储信息
  Session[“myname”]=”Mike”;
  file://获得信息
  myname=Session[“myname”];
  
    C、数据库
  
    数据库将使我们能够存储大量的与Web应用程序中的状态相关的信息,有时,用户会使用唯一的ID频繁地访问数据库,我们可以将它存储在数据库中,在对网站中网页的多次请求中使用。
    总结
  
    ASP.NET中的功能和工具比ASP中更多,使我们能够更有效和高效地管理网页的状态。具体选择哪种方法与你的应用程序有关,在选择时可以考虑下面的问题:
  
    ·需要存储多少信息?
    ·客户端接受持久的还是内存中的cookie?
    ·希望在客户端还是在服务器端存储信?
    ·要存储的信息需要保密吗?  
    ·希望你的网页的性能如何?  

     //nothing to do..just create to object
   }
  
   public POP3client(string pop_server,string user_name,string password)
   {
   //put the specied server (pop_server), user (user_name) and password (password)
   //into the appropriate properties.
   pop=pop_server;
   user=user_name;
   pwd=password;
   }
  
   #region Utility Methods, some public, some private
   public string connect (string pop_server)
   {
   pop=pop_server; //put the specified server into the pop property
   return(connect()); //call the connect method
   }
   public string connect()
   {
   //Initialize to the pop server. This code snipped "borrowed"
   //with some modifications...
   //from the article "Retrieve Mail From a POP3 Server Using C#" at
   //www.codeproject.com by Agus Kurniawan
   //http://www.codeproject.com/csharp/popapp.asp
  
   // create server with port 110
   Server = new TcpClient(pop,110);
  
   try
   {
   // initialization
   NetStrm = Server.GetStream();
   RdStrm= new StreamReader(Server.GetStream());
  
   //The pop session is now in the AUTHORIZATION state
   state=connect_state.AUTHORIZATION ;
   return(RdStrm.ReadLine ());
   }
   catch(InvalidOperationException err)
   {
   return("Error: "+err.ToString());
   }
  
   }
   private string disconnect ()
   {
   string temp="disconnected successfully.";
   if(state !=connect_state.disc)
   {
  
   //close connection
   NetStrm.Close();
   RdStrm.Close();
   state=connect_state.disc ;
   }
   else
   {
   temp="Not Connected.";
   }
   return(temp);
   }
  
   private void issue_command(string command)
   {
   //send the command to the pop server. This code snipped "borrowed"
   //with some modifications...
   //from the article "Retrieve Mail From a POP3 Server Using C#" at
   //www.codeproject.com by Agus Kurniawan
   //http://www.codeproject.com/csharp/popapp.asp
   Data= command + CRLF;
   szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
   NetStrm.Write(szData,0,szData.Length);
  
   }
   private string read_single_line_response()
   {
   //read the response of the pop server. This code snipped "borrowed"
   //with some modifications...
   //from the article "Retrieve Mail From a POP3 Server Using C#" at
   //www.codeproject.com by Agus Kurniawan
   //http://www.codeproject.com/csharp/popapp.asp
   string temp;
   try
   {
   temp = RdStrm.ReadLine();
   was_pop_error(temp);
   return(temp);

    }
   catch(InvalidOperationException err)
   {
   return("Error in read_single_line_response(): " + err.ToString ()) ;
   }
  
   }

 

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页  

 

   private string read_multi_line_response()
   {
   //read the response of the pop server. This code snipped "borrowed"
   //with some modifications...
   //from the article "Retrieve Mail From a POP3 Server Using C#" at
   //www.codeproject.com by Agus Kurniawan
   //http://www.codeproject.com/csharp/popapp.asp
   string temp="";
   string szTemp;
  
   try
   {
   szTemp = RdStrm.ReadLine();
   was_pop_error(szTemp);
   if(!error)
   {
  
   while(szTemp!=".")
   {
   temp += szTemp+CRLF;
   szTemp = RdStrm.ReadLine();
   }
   }
   else
   {
   temp=szTemp;
   }
   return(temp);
   }
   catch(InvalidOperationException err)
   {
   return("Error in read_multi_line_response(): " + err.ToString ());
   }
   }
   private void was_pop_error(string response)
   {
   //detect if the pop server that issued the response believes that
   //an error has occured.
  
   if(response.StartsWith ("-"))
   {
   //if the first character of the response is "-" then the
   //pop server has encountered an error executing the last
   //command send by the client
   error=true;
   }
   else
   {
   //success
   error=false;
   }
   }
   #endregion
   #region POP commands
   public string DELE(int msg_number)
   {
   string temp;
  
   if (state != connect_state.TRANSACTION )
   {
   //DELE is only valid when the pop session is in the TRANSACTION STATE
   temp="Connection state not = TRANSACTION";
   }
   else
   {
   issue_command("DELE " + msg_number.ToString ());
   temp=read_single_line_response();
   }
   return(temp);
   }
  
   public string LIST()
   {
   string temp="";
   if (state != connect_state.TRANSACTION )
   {
   //the pop command LIST is only valid in the TRANSACTION state
   temp="Connection state not = TRANSACTION";
   }
   else
   {
   issue_command ("LIST");
   temp=read_multi_line_response();

    ASP.NET中的状态管理
  
   }
   return(temp);
   }
  
   public string LIST(int msg_number)
   {
   string temp="";
  
   if (state != connect_state.TRANSACTION )
   {
   //the pop command LIST is only valid in the TRANSACTION state
   temp="Connection state not = TRANSACTION";
   }
   else
   {
   issue_command ("LIST " + msg_number.ToString ());
   temp=read_single_line_response(); //when the message number is supplied, expect a single line response
   }
   return(temp);
  
   }
  
   public string NOOP()
   {
   string temp;
   if (state != connect_state.TRANSACTION )
   {
   //the pop command NOOP is only valid in the TRANSACTION state
   temp="Connection state not = TRANSACTION";
   }
   else
   {
   issue_command ("NOOP");
   temp=read_single_line_response();
  
   }
   return(temp);
  
   }
   public string PASS()
   {
   string temp;
   if (state != connect_state.AUTHORIZATION)
   {
   //the pop command PASS is only valid in the AUTHORIZATION state
   temp="Connection state not = AUTHORIZATION";
   }
   else
   {
   if (pwd !=null)
   {
   issue_command ("PASS " + pwd);
   temp=read_single_line_response();
  
   if (!error)
   {
   //transition to the Transaction state
   state=connect_state.TRANSACTION;
   }
   }
   else
   {
   temp="No Password set.";
   }
   }
   return(temp);
   }
   public string PASS(string password)
   {
   pwd=password; //put the supplied password into the appropriate property
   return(PASS()); //call PASS() with no arguement
   }
  

 

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页  

 

   public string QUIT()
   {
   //QUIT is valid in all pop states
  
   string temp;
   if (state !=connect_state.disc)
   {
   issue_command ("QUIT");
   temp=read_single_line_response();
   temp += CRLF + disconnect();
  
   }
   else
   {
   temp="Not Connected.";
   }
   return(temp);
  
   }
   public string RETR (int msg)
   {
   string temp="";
   if (state != connect_state.TRANSACTION )
   {
   //the pop command RETR is only valid in the TRANSACTION state
   temp="Connection state not = TRANSACTION";  

  }
   else
   {
   // retrieve mail with number mail parameter
   issue_command ("RETR "+ msg.ToString ());
   temp=read_multi_line_response();
   }
   return(temp);
  
   }
  
   public string RSET()
   {
   string temp;
   if (state != connect_state.TRANSACTION )
   {
   //the pop command STAT is only valid in the TRANSACTION state
   temp="Connection state not = TRANSACTION";
   }
   else
   {
   issue_command("RSET");
   temp=read_single_line_response();
   }
   return(temp);
  
   }
  
   public string STAT()
   {
   string temp;
   if (state==connect_state.TRANSACTION)
   {
   issue_command("STAT");
   temp=read_single_line_response();
  
   return(temp);
   }
   else
  
   {
   //the pop command STAT is only valid in the TRANSACTION state
   return ("Connection state not = TRANSACTION");
   }
   }
  
   public string USER()
   {
   string temp;
   if (state != connect_state.AUTHORIZATION)
   {
   //the pop command USER is only valid in the AUTHORIZATION state
   temp="Connection state not = AUTHORIZATION";
   }
   else
   {
   if (user !=null)
   {
   issue_command("USER "+ user);
   temp=read_single_line_response();
   }
   else
   { //no user has been specified
   temp="No User specified.";
   }
   }
   return(temp);
   }
  
   public string USER(string user_name)
   {
   user=user_name; //put the user name in the appropriate propertity
   return(USER()); //call USER with no arguements
   }
   #endregion
   }
  
  }

     NOTE: You must import the following namespace:
  ' Imports System.IO
  ' Without this import statement at the beginning
  ' of your code, the example will not function.
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
  Dim sr As New StreamReader(OpenFileDialog1.FileName)
  MessageBox.Show(sr.ReadToEnd)
  sr.Close()
  End If
  End Sub
  
  // C#
  // NOTE: You must import the following namespace:
  // using System.IO;
  // Without this import statement at the beginning
  // of your code, the example will not function.
  private void button1_Click(object sender, System.EventArgs e)
  {
  if(openFileDialog1.ShowDialog() == DialogResult.OK)
  {
  StreamReader sr = new StreamReader(openFileDialog1.FileName);
  MessageBox.Show(sr.ReadToEnd());
  sr.Close();
  }
  }
  

 

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页  

 

  打开文件还可以使用 OpenFileDialog 组件的 OpenFile 方法,它将返回文件的每一个字节。在下面的例子中,一个 OpenFileDialog 组件将被实例化,它使用了 cursor 过滤器,以限定用户只能选取光标文件(扩展名为 .cur)。一旦某个 .cur 文件被选中,窗体的光标就被设成该文件描绘的光标形状。
  
  本例假设存在名为 Button1 的 Button 控件。
  
  ' Visual Basic
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  ' Display an OpenFileDialog so the user can select a Cursor.
  Dim openFileDialog1 As New OpenFileDialog()
  openFileDialog1.Filter = "Cursor Files*.cur"
  openFileDialog1.Title = "Select a Cursor File"
  
  ' Show the Dialog.
  ' If the user clicked OK in the dialog and
  ' a .CUR file was selected, open it.
  If openFileDialog1.ShowDialog() = DialogResult.OK Then
  If openFileDialog1.FileName <> "" Then
  ' Assign the cursor in the Stream to the Form's Cursor property.
  Me.Cursor = New Cursor(openFileDialog1.OpenFile())
  End If
  End If
  End Sub
  
  // C#
  private void button1_Click(object sender, System.EventArgs e)
  {
  // Display an OpenFileDialog so the user can select a Cursor.
  OpenFileDialog openFileDialog1 = new OpenFileDialog();
  openFileDialog1.Filter = "Cursor Files*.cur";
  openFileDialog1.Title = "Select a Cursor File";
  
  // Show the Dialog.
  // If the user clicked OK in the dialog and
  // a .CUR file was selected, open it.
  if (openFileDialog1.ShowDialog() == DialogResult.OK)
  {
  if(openFileDialog1.FileName != "")
  {
  // Assign the cursor in the Stream to the Form's Cursor property.
  this.Cursor = new Cursor(openFileDialog1.OpenFile());
  }
  }
  }
  
  关于读取文件流的进一步信息,请参阅FileStream.BeginRead 方法。
  
  SaveFileDialog 组件
  
  本对话框允许用户浏览文件系统并且选取将被写入的文件。当然,你还必须为文件写入编写具体代码。
  
  下列代码通过 Button 控件的 Click 事件调用 SaveFileDialog 组件。当用户选中某个文件,并且单击 OK 的时候,RichTextBox 控件里的内容将被保存到所选的文件中。
  
  本例假设存在名为 Button1 的 Button 控件,名为 RichTextBox1 的 RichTextBox 控件和名为 OpenFileDialog1 的 SaveFileDialog 控件。
  
  ' Visual Basic
  ' NOTE: You must import the following namespace:
  ' Imports System.IO
  ' Without this import statement at the beginning
  ' of your code, the code example will not function.
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
  RichTextBox1.SaveFile(SaveFileDialog1.FileName, _
  RichTextBoxStreamType.PlainText)
  End If
  End Sub
  
  // C#
  // NOTE: You must import the following namespace:
  // using System.IO;
  // Without this import statement at the beginning
  // of your code, the code example will not function.
  private void button1_Click(object sender, System.EventArgs e)
  {
  if((saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
  richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
  }
  }
  
  保存文件还可以用 SaveFileDialog 组件的 OpenFile 方法,它将提供一个用于写入的 Stream 对象。
  
  在下面的例子中,有一个包含图片的 Button 控件。 当你单击这个按钮的时候,一个 SaveFileDialog 组件将被打开,它将使用 .gif 、 .jpeg 和 .bmp 类型的文件过滤器。一旦用户通过 Save File 对话框内选中此类文件,按钮上的图片将被存入其中。
  
  本例假设存在名为 Button2 的 Button 控件,并且它的 Image 属性被设为某个扩展名为 .gif 、 .jpeg 或者 .bmp 的图片文件。
  
  'Visual Basic
  ' NOTE: You must import the following namespaces:
  ' Imports System.IO
  ' Imports System.Drawing.Imaging
  ' Without these import statements at the beginning of your code,
  ' the code example will not function.
  Private Sub Button2_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button2.Click
  ' Display an SaveFileDialog so the user can save the Image
  ' assigned to Button2.
  Dim saveFileDialog1 As New SaveFileDialog()
  saveFileDialog1.Filter = "JPeg Image*.jpgBitmap Image*.bmpGif Image*.gif"
  saveFileDialog1.Title = "Save an Image File"
  saveFileDialog1.ShowDialog()
  
  ' If the file name is not an empty string open it for saving.
  If saveFileDialog1.FileName <> "" Then
  ' Save the Image via a FileStream created by the OpenFile method.

     Dim fs As FileStream = CType(saveFileDialog1.OpenFile(), FileStream)
  ' Save the Image in the appropriate ImageFormat based upon the
  ' file type selected in the dialog box.
  ' NOTE that the FilterIndex property is one-based.
  Select Case saveFileDialog1.FilterIndex
  Case 1
  Me.button2.Image.Save(fs, ImageFormat.Jpeg)
  
  Case 2
  Me.button2.Image.Save(fs, ImageFormat.Bmp)
  
  Case 3
  Me.button2.Image.Save(fs, ImageFormat.Gif)
  End Select
  
  fs.Close()
  End If
  End Sub
  

 

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页  

 

  // C#
  // NOTE: You must import the following namespaces:
  // using System.IO;
  // using System.Drawing.Imaging;
  // Without these import statements at the beginning of your code,
  // the code example will not function.
  private void button2_Click(object sender, System.EventArgs e)
  {
  // Display an SaveFileDialog so the user can save the Image
  // assigned to Button2.
  SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  saveFileDialog1.Filter = "JPeg Image*.jpgBitmap Image*.bmpGif Image*.gif";
  saveFileDialog1.Title = "Save an Image File";
  saveFileDialog1.ShowDialog();
  
  // If the file name is not an empty string open it for saving.
  if(saveFileDialog1.FileName != "")
  {
  // Save the Image via a FileStream created by the OpenFile method.
  FileStream fs = (FileStream)saveFileDialog1.OpenFile();
  // Save the Image in the appropriate ImageFormat based upon the
  // File type selected in the dialog box.
  // NOTE that the FilterIndex property is one-based.
  switch(saveFileDialog1.FilterIndex)
  {
  case 1 :
  this.button2.Image.Save(fs,ImageFormat.Jpeg);
  break;
  
  case 2 :
  this.button2.Image.Save(fs,ImageFormat.Bmp);
  break;
  
  case 3 :
  this.button2.Image.Save(fs,ImageFormat.Gif);
  break;
  }
  
  fs.Close();
  }
  }
  
  
  关于写入文件流的进一步信息,请参阅 FileStream.BeginWrite 方法。
  
  ColorDialog 组件
  
  此对话框显示颜色列表,并且返回所选的颜色。
  
  与前两种对话框不同,ColorDialog 组件很容易实现其主要功能(挑选颜色)。选取的颜色将成为 Color 属性的设定值。因此,使用颜色就和设定属性值一样简单。在下面的例子中,按钮控制的 Click 事件将会开启一个 ColorDialog 组件。一旦用户选中某种颜色,并且单击了 OK ,按钮的背景将被设成所选的颜色。本例假设存在名为 Button1 的 Button 组件和名为 ColorDialog1 的 ColorDialog 组件。
  
  ' Visual Basic
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  If ColorDialog1.ShowDialog() = DialogResult.OK Then
  Button1.BackColor = ColorDialog1.Color
  End If
  End Sub
  
  // C#
  private void button1_Click(object sender, System.EventArgs e)
  {
  if(colorDialog1.ShowDialog() == DialogResult.OK)
  {
  button1.BackColor = colorDialog1.Color;
  }
  }
  
  
  ColorDialog 组件具有 AllowFullOpen 属性。当其设为 False 的时候,Define Custom Colors 按钮将会失效,此时用户只能使用预定义的调色板。此外,它还有一个 SolidColorOnly 属性,当其设为 true 时,用户将不能使用抖动颜色。
  
  FontDialog 组件
  
  此对话框允许用户选择字体,以改变其 weight 和 size 等属性。
  
  被选中的字体将成为 Font 属性的设定值。因此,使用字体也和设定属性值一样简单。在本例通过 Button 控件的 Click 事件调用 FileDialog 组件。当用户选中一个字体,并且单击 OK 的时候,TextBox 控件的 Font 属性将被设成所选的字体。本例假设存在名为 Button1 的 Button 控件,名为 TextBox1 的 TextBox 控件和名为 FontDialog1 的 FontDialog 组件。
  
  ' Visual Basic
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  If FontDialog1.ShowDialog() = DialogResult.OK Then
  TextBox1.Font = FontDialog1.Font
  End If
  End Sub
  
  // C#
  private void button1_Click(object sender, System.EventArgs e)
  {
  if(fontDialog1.ShowDialog() == DialogResult.OK)
  {
  textBox1.Font = fontDialog1.Font;
  }
  }
  
  FontDialog 元件还包括 MinSize 和 MaxSize 属性,它们决定了允许用户选择的字体的最小和最大点数;还有一个 ShowColor 属性,当其设为 True 时,用户可以从对话框的下拉列表中选取字体的颜色。 
   

 

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页  

 

  PrintDocument 类
  
  以下三个会话框,PrintDialog 组件、 PageSetupDialog 组件和 PrintPreviewDialog 控件,都与 PrintDocument 类有关。PrintDocument 类用于文档打印前的设置:设定其属性,以改变文档外观和打印方式,再将其实例输出到打印机。通常的步骤是:
  (1) 生成 PrintDocument 类的一个实例;
  (2) 设置 PageSetupDialog 组件的属性;
  (3) 使用 PrintPreviewDialog 控件进行预览;
  (4) 通过 PrintDialog 组件打印出来。
  
  关于 PrintDocument 类的进一步资料,请参阅 PrintDocument Class 。
  
  PrintDialog 元件
  
  此对话框允许用户指定将要打印的文档。除此之外,它还能用于选择打印机、决定打印页,以及设置打印相关属性。通过它可以让用户文档打印更具灵活性:他们既能打印整个文档,又能打印某个片断,还能打印所选区域。
  
  使用 PrintDialog 组件时要注意它是如何与 PrinterSettings 类进行交互的。PrinterSettings 类用于设定纸张来源、分辨率和加倍放大等打印机特征属性。每项设置都是 PrinterSettings 类的一个属性。通过 PrintDialog 类可以改变关联到文档的 PrinterSetting 类实例(由PrintDocument.PrinterSettings 指定)的特征属性值。
  
  PrintDialog 组件将包含特征属性设置的 PrintDocument 类的实例提交到打印机。应用 PrintDialog 组件进行文档打印的范例,请参见 Creating Standard Windows Forms Print Jobs。
  
  PageSetupDialog 组件
  
  PageSetupDialog 组件用于显示打印布局、纸张大小和其它页面选项。如同其他对话框一样,可以通过 ShowDialog 方法调用 PageSetupDialog 组件。此外,必须生成一个 PrintDocument 类的实例,也即被打印的文档;而且必须安装了一台本地或者远程打印机,否则,PageSetupDialog 组件将无法获取打印格式以供用户选择。
  
  使用 PageSetupDialog 组件时必须注意它是如何与 PageSettings 类进行交互的。PageSettings 类决定页面如何被打印,比如打印方向、页面大小和边距等。每项设置都是 PageSettings 类的一个属性。PageSetupDialog 类可以改变 PageSettings 类实例(由 PrintDocument.DefaultPageSettings 指定)的上述选项。
  
  在下列代码中,Button 控件的 Click 事件处理程序开启一个 PageSetupDialog 组件;其 Document 属性被设成某个存在的文档;其 Color 属性被设成 false 。
  
  本例假设存在名为 Button1 的 Button 控件、名为 myDocument 的 PrintDocument 控件和名为 PageSetupDialog1 的 PageSetupDialog 组件。
  
  ' Visual Basic  

     Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  ' The print document 'myDocument' used below
  ' is merely for an example.
  'You will have to specify your own print document.
  PageSetupDialog1.Document = myDocument
  ' Set the print document's color setting to false,
  ' so that the page will not be printed in color.
  PageSetupDialog1.Document.DefaultPageSettings.Color = False
  PageSetupDialog1.ShowDialog()
  End Sub
  
  // C#
  private void button1_Click(object sender, System.EventArgs e)
  {
  // The print document 'myDocument' used below
  // is merely for an example.
  // You will have to specify your own print document.
  pageSetupDialog1.Document = myDocument;
  // Set the print document's color setting to false,
  // so that the page will not be printed in color.
  pageSetupDialog1.Document.DefaultPageSettings.Color = false;
  pageSetupDialog1.ShowDialog();
  }
  
  PrintPreviewDialog 控件
  
  与其他对话框不同,PrintPreviewDialog 控件对整个应用程序或者其它控件没有影响,因为它仅仅在对话框里显示内容。此对话框用于显示文档,主要是打印之前的预览。
  
  调用 PrintPreviewDialog 控件,也是使用 ShowDialog 方法。同时,必须生成 PrintDocument 类的一个实例,也即被打印的文档。
  
  注意:当使用 PrintPreviewDialog 控件时,也必须已经安装了一台本地或者远程打印机,否则 PrintPreviewDialog 组件将无法获取被打印文档的外观。
  
  PrintPreviewDialog 控件通过 PrinterSettings 类和 PageSettings 类进行设置,分别与 PageDialog 组件和 PageSetupDialog 组件相似。此外,PrintPreviewDialog 控件的 Document 属性所指定的被打印文档,同时作用于 PrinterSettings 类和 PageSettings 类,其内容被显示在预览窗口中。
  
  在下列代码中,通过 Button 控件的 Click 事件调用 PrintPreviewDialog 控件。被打印文档在 Document 属性中指定。注意:代码中没有指定被打印文档。
  
  本例假设存在名为 Button1 的 Button 控件,名为 myDocument 的 PrintDocument 组件和名为 PrintPreviewDialog1 的 PrintPreviewDialog 控件。
  
  
  ' Visual Basic
  Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button1.Click
  ' The print document 'myDocument' used below
  ' is merely for an example.
  ' You will have to specify your own print document.
  PrintPreviewDialog1.Document = myDocument
  PrintPreviewDialog1.ShowDialog()
  End Sub
  
  // C#
  private void button1_Click(object sender, System.EventArgs e)
  {
  // The print document 'myDocument' used below
  // is merely for an example.
  // You will have to specify your own print document.
  printPreviewDialog1.Document = myDocument;
  printPreviewDialog1.ShowDialog()
  }
  
  小结
  .NET 框架里包含了 Windows 用户所熟悉的各种公共对话框,于是在应用程序中提供交互功能变得更加容易。通常,对话框的用途是多种多样的;.NET 框架对此提供了开放支持,你可以选择最佳方案以适合应用程序的需要。我们介绍了与对话框组件有关的一些简单应用。你可以直接使用这些代码,也可以对其稍加修改用于你的应用程序。

 

上一页  [1] [2] [3] [4] [5] [6] [7] 


上一篇:ASP.NET中Session的状态保持方式-ASP.NET
下一篇:ASP.Net安装简明手册 -ASP.NET

本篇新闻:ASP.NET中的状态管理-ASP.NET

相关新闻
相关评论
 
评论表单加载中...
 
Asp.Net文章

 在Visual C++应

 编辑:admin

 时间:2008-3-10


   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
最新文章
   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
总站搜索
搜索
 
热门文章
   oracle数据库文件中的导入\导出
   用Oracle10g列值掩码技术隐藏敏感数据
   VB程序中用ADO对象动态创建数据库和表-VB.NET
   用VB6写简单程序 让电骡自动关机-VB.NET
   使用.NET2.0编写COM组件供VB调用-VB.NET
   VB.NET:键盘控制焦点移动-VB.NET
   用VB.NET绘制GDI图形-VB.NET
   vb.net中应用 ArrayList 实例-VB.NET
 
推荐文章
ASP.NET中的状态管理-ASP.NET
VC、IE、ASP环境下打印、预备的完美解决方案
oracle数据库文件中的导入\导出
VB.NET中快速访问注册表技巧-VB.NET
在vb中实现超连接的方法!和直接发邮件-VB.NET
用VB做realplayer播放列表-VB.NET
在VB.NET中如何实现和利用SortedLists-VB.NET
利用VB.NET Stopwatch对象记录时间-VB.NET
成都古羌科技有限公司版权所有: Copyright@2007-2010 ,ALL Rights Reserved 蜀ICP备07017240号