请问Show, Showdialog, Run ,Dispose作用?

ChenSu2008 2006-05-26 10:59:16
1.
什么时候用
Application.Run(form);
什么时候用
form.Show(), form.Showdialog()
请说说区别及为什么这么用。

2.
Dispose 的作用是什么,它能保证对象被析构吗?
...全文
264 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yellow198267 2006-05-26
  • 打赏
  • 举报
回复
Show是你打开非模态对话框的时候用,它不阻塞当前线程
Showdialog相反。
Application.Run(form);一般是应用程序主窗体用
Dispose 释放资源,能不能保证资源释放就要看你的代码和gc了

-----------------------------------------------------------------

正解~~~~~
diandian82 2006-05-26
  • 打赏
  • 举报
回复
Show是你打开非模态对话框的时候用,它不阻塞当前线程
Showdialog相反。
Application.Run(form);一般是应用程序主窗体用
Dispose 释放资源,能不能保证资源释放就要看你的代码和gc了
ChenSu2008 2006-05-26
  • 打赏
  • 举报
回复
呵呵,我希望有人说说,那个上面的我觉得的不太通俗。
Firestone2003 2006-05-26
  • 打赏
  • 举报
回复
MSDN上有比较详细的解释,按照你的问题搜索就行了
zhzh75370782 2006-05-26
  • 打赏
  • 举报
回复
查MSDN吧
liujiwe79 2006-05-26
  • 打赏
  • 举报
回复
Show打开非模态对话框,它不阻塞当前线程
Showdialog打开模态对话框。
Application.Run(form);一般是应用程序主窗体用,在main方法中用
Dispose 释放资源,能不能保证资源释放就要看你的代码和gc了
Magic_kui_asd 2006-05-26
  • 打赏
  • 举报
回复
说白了form.Showdialog():必须先关掉本窗口后才可以处理其他窗口
form.Show():可以随便处理显示的任何窗口即其他窗口
Application.Run()方法:在当前线程上开始运行标准应用程序消息循环(我也不太明白),一般是应用程序主窗体(就是首先出现的窗体)用。
Dispose 用于释放资源。
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; namespace DormMIS { /// /// Form1 的摘要说明。 /// public class Login : System.Windows.Forms.Form { private System.Windows.Forms.Button btClose;//取消按钮 private System.Windows.Forms.Button btAdd; private System.Windows.Forms.TextBox password; private System.Windows.Forms.TextBox name; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; private OleDbConnection oleConnection1 = null; public Login() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); this.oleConnection1=new OleDbConnection(DormMIS.database.dbConnection.connection); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login)); this.btClose = new System.Windows.Forms.Button(); this.btAdd = new System.Windows.Forms.Button(); this.password = new System.Windows.Forms.TextBox(); this.name = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btClose // this.btClose.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btClose.ForeColor = System.Drawing.Color.Black; this.btClose.Location = new System.Drawing.Point(168, 156); this.btClose.Name = "btClose"; this.btClose.Size = new System.Drawing.Size(75, 23); this.btClose.TabIndex = 20; this.btClose.Text = "取消"; this.btClose.Click += new System.EventHandler(this.btClose_Click); // // btAdd // this.btAdd.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btAdd.ForeColor = System.Drawing.Color.Black; this.btAdd.Location = new System.Drawing.Point(48, 156); this.btAdd.Name = "btAdd"; this.btAdd.Size = new System.Drawing.Size(75, 23); this.btAdd.TabIndex = 19; this.btAdd.Text = "确定"; this.btAdd.Click += new System.EventHandler(this.btAdd_Click); // // password // this.password.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.password.Location = new System.Drawing.Point(128, 116); this.password.Name = "password"; this.password.PasswordChar = '*'; this.password.Size = new System.Drawing.Size(100, 21); this.password.TabIndex = 18; this.password.Text = "admin"; // // name // this.name.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.name.Location = new System.Drawing.Point(128, 76); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(100, 21); this.name.TabIndex = 17; this.name.Text = "admin"; this.name.TextChanged += new System.EventHandler(this.name_TextChanged); // // label3 // this.label3.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(64, 116); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 23); this.label3.TabIndex = 16; this.label3.Text = "密 码"; // // label2 // this.label2.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.ForeColor = System.Drawing.Color.Black; this.label2.Location = new System.Drawing.Point(64, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 23); this.label2.TabIndex = 15; this.label2.Text = "用户名"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(40, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(228, 28); this.label1.TabIndex = 14; this.label1.Text = "宿舍管理信息系统"; // // Login // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.BackColor = System.Drawing.Color.Ivory; this.ClientSize = new System.Drawing.Size(304, 210); this.Controls.Add(this.btClose); this.Controls.Add(this.btAdd); this.Controls.Add(this.password); this.Controls.Add(this.name); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Login"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "登录"; this.Load += new System.EventHandler(this.Login_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.Run(new Login()); } private void btAdd_Click(object sender, System.EventArgs e) { if(name.Text.Trim()==""||password.Text.Trim()=="") MessageBox.Show("请输入用户名和密码","提示"); else { oleConnection1.Open(); OleDbCommand cmd=new OleDbCommand("",oleConnection1); string sql="select * from userinfo where UName='"+name.Text.Trim()+"' and PWD='"+password.Text.Trim()+"'"; cmd.CommandText=sql; if (null!=cmd.ExecuteScalar()) { //隐藏登录窗口 this.Visible=false; //创建并打开主界面 Main main=new Main(); main.Tag=this.FindForm(); OleDbDataReader dr; cmd.CommandText=sql; dr=cmd.ExecuteReader(); dr.Read(); main.statusBarPanel2.Text=name.Text.Trim(); main.ShowDialog(); } else MessageBox.Show("用户名或密码错误","警告"); } oleConnection1.Close(); } private void btClose_Click(object sender, System.EventArgs e) { this.Close(); } private void name_TextChanged(object sender, EventArgs e) { } } }
给初学者的简单例题! private System.ComponentModel.IContainer components; private const int kNumberOfRows = 8; private const int kNumberOfTries = 3; private int NumTotalBricks = 0; private int NumBalls = 0; private Ball TheBall = new Ball(); private Paddle ThePaddle = new Paddle(); private System.Windows.Forms.Timer timer1; private Row[] Rows = new Row[kNumberOfRows]; private Score TheScore = null; private Thread oThread = null; [DllImport("winmm.dll")] public static extern long PlaySound(String lpszName, long hModule, long dwFlags); public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); for (int i = 0; i < kNumberOfRows; i++) { Rows[i] = new Row(i); } ThePaddle.Position.X = 5; ThePaddle.Position.Y = this.ClientRectangle.Bottom - ThePaddle.Height; TheBall.Position.Y = this.ClientRectangle.Bottom - 200; this.SetBounds(this.Left, this.Top, Rows[0].GetBounds().Width, this.Height); TheScore = new Score(ClientRectangle.Right - 50, ClientRectangle.Bottom - 180); // choose Level SpeedDialog dlg = new SpeedDialog(); if (dlg.ShowDialog() == DialogResult.OK) { timer1.Interval = dlg.Speed; } // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private string m_strCurrentSoundFile = "BallOut.wav"; public void PlayASound() { if (m_strCurrentSoundFile.Length > 0) { PlaySound(Application.StartupPath + "\\" + m_strCurrentSoundFile, 0, 0); } m_strCurrentSoundFile = ""; oThread.Abort(); } public void PlaySoundInThread(string wavefile) { m_strCurrentSoundFile = wavefile; oThread = new Thread(new ThreadStart(PlayASound)); oThread.Start(); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(552, 389); this.KeyPreview = true; this.Name = "Form1"; this.Text = "Brick Out"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height); TheScore.Draw(g); ThePaddle.Draw(g); DrawRows(g); TheBall.Draw(g); } private void DrawRows(Graphics g) { for (int i = 0; i < kNumberOfRows; i++) { Rows[i].Draw(g); } } private void CheckForCollision() { if (TheBall.Position.X < 0) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y this.ClientRectangle.Right - TheBall.Width ) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y > this.ClientRectangle.Bottom - TheBall.YStep) // lost the ball! { IncrementGameBalls(); Reset(); PlaySoundInThread("BallOut.wav"); } if (RowsCollide(TheBall.Position)) { TheBall.YStep *= -1; PlaySoundInThread("BrickHit.wav"); } int hp = HitsPaddle(TheBall.Position); if (hp > -1)// lost the ball! { PlaySoundInThread("PaddleHit.wav"); switch (hp) { case 1: TheBall.XStep = -7; TheBall.YStep = -3; break; case 2: TheBall.XStep = -5; TheBall.YStep = -5; break; case 3: TheBall.XStep = 5; TheBall.YStep = -5; break; default: TheBall.XStep = 7; TheBall.YStep = -3; break; } } } private int HitsPaddle(Point p) { Rectangle PaddleRect = ThePaddle.GetBounds(); if (p.Y >= this.ClientRectangle.Bottom - (PaddleRect.Height + TheBall.Height) ) { if ((p.X > PaddleRect.Left) && (p.X PaddleRect.Left) && (p.X PaddleRect.Left + PaddleRect.Width/4) && (p.X PaddleRect.Left + PaddleRect.Width/2) && (p.X = kNumberOfTries) { timer1.Stop(); string msg = "Game Over\nYou knocked out " + NumTotalBricks; if (NumTotalBricks == 1) msg += " brick."; else msg += " bricks."; MessageBox.Show(msg); Application.Exit(); } } private void Reset() { TheBall.XStep = 5; TheBall.YStep = 5; TheBall.Position.Y = this.ClientRectangle.Bottom - 190; TheBall.Position.X = 5; timer1.Stop(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); } private int SumBricks () { int sum = 0; for (int i = 0; i < kNumberOfRows; i++) { sum += Rows[i].BrickOut; } return sum; } private bool RowsCollide (Point p) { for (int i = 0; i < kNumberOfRows; i++) { if (Rows[i].Collides(TheBall.GetBounds())) { Rectangle rRow = Rows[i].GetBounds(); Invalidate(rRow); return true; } } return false; } private void timer1_Tick(object sender, System.EventArgs e) { TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); TheBall.Move(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); CheckForCollision(); NumTotalBricks = SumBricks(); TheScore.Count = NumTotalBricks; Invalidate(TheScore.GetFrame()); if (NumTotalBricks == kNumberOfRows*Row.kNumberOfBricks) { timer1.Stop(); MessageBox.Show("You Win! You knocked out all the bricks!"); Application.Exit(); } } private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { string result = e.KeyData.ToString(); Invalidate(ThePaddle.GetBounds()); switch (result) { case "Left": ThePaddle.MoveLeft(); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; case "Right": ThePaddle.MoveRight(ClientRectangle.Right); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; default: break; } }
package com.ui.server; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ServerBootFrame extends JFrame { /** * */ private static final long serialVersionUID = 1L; JPanel jp = new JPanel(new BorderLayout()); JPanel jp1 = new JPanel(new FlowLayout()); JScrollPane jsp1 = new JScrollPane(); JButton jbStart = new JButton("启动"); JButton jbEnd = new JButton("关闭"); JTextArea jtaState = new JTextArea(10, 25); Font font = new Font("Serif", Font.BOLD, 18); Color fore = Color.YELLOW; Color back = new Color(81, 217, 251); public ServerBootFrame(String title) { super(title); this.getContentPane().add(jp); jp.add(jsp1, "Center"); jsp1.getViewport().add(jtaState); jp.add(jp1, "South"); jp1.add(jbStart); jp1.add(jbEnd); jtaState.setFont(font); jtaState.setForeground(fore); jtaState.setBackground(back); jp1.setBackground(back); this.setResizable(false); this.setLocation(250, 250); } public void showFrame() { this.pack(); this.setVisible(true); } public void bootingServer(final BootEndInterface bt) { this.jbStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bt.boot(); } }); } public void endingServer(final BootEndInterface ed) { this.jbEnd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ed.end(); } }); } public void closeWindow(final BootEndInterface ed) { this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e1) { ed.end(); } }); } public void appendStringTojtaState(String str) { jtaState.append(str); } } package com.ui.client; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.sql.*; public class LoginFrame extends JFrame { JLabel jUserName=new JLabel("用户姓名:"); JLabel jUserPsd=new JLabel("用户密码:"); JTextField txtUserName=new JTextField("",10); JPasswordField txtUserPsd=new JPasswordField(10); JButton okButton=new JButton("确定"); JButton regButton=new JButton("注册"); JPanel jp=new JPanel(new GridLayout(2,1)); JPanel jp1=new JPanel(new FlowLayout(FlowLayout.CENTER)); JPanel jp2=new JPanel(new FlowLayout(FlowLayout.LEFT)); JPanel jp3=new JPanel(new FlowLayout()); Font f=new Font("Serif",Font.BOLD,15); public LoginFrame() { super("用户登陆界面"); this.setLocation(250,250); this.getContentPane().add(jp,"Center"); this.getContentPane().add(jp3,"South"); jp.add(jp1);jp.add(jp2); jp1.add(jUserName);jp1.add(txtUserName); jp2.add(jUserPsd);jp2.add(txtUserPsd); jp3.add(okButton);jp3.add(regButton); txtUserName.setFont(f); txtUserPsd.setFont(f); txtUserPsd.setEchoChar('x'); txtUserName.setToolTipText("请输入用户名"); txtUserPsd.setToolTipText("请输入用户密码"); okButton.addActionListener(new SolveButtonEvent(1)); regButton.addActionListener(new SolveButtonEvent(2)); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void showWindow() { this.pack(); this.setVisible(true); } public void closeWindow() { this.dispose(); } public String getUserName() { return this.txtUserName.getText().trim(); } public String getUserPassword() { return new String(this.txtUserPsd.getPassword()); } class SolveButtonEvent implements ActionListener { int select=0; public SolveButtonEvent(int select) { this.select=select; } public void actionPerformed(ActionEvent e) { //int x=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getX(); //int y=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getY(); String userName=LoginFrame.this.getUserName(); String userPsd=LoginFrame.this.getUserPassword(); int nameLength=userName.length(); int psdLength=userPsd.length(); if(select==1) { if(nameLength>0 && psdLength>0 ) { if(LoginFrame.this.query(userName,userPsd)==true) { LoginFrame.this.closeWindow(); //new Client(); } else { MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","错误!","用户名或密码错误.\n登陆失败"); md.showDialog(); } } else { if(nameLength==0) { MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户名不能为空"); md.showDialog(); } else if(psdLength==0) { MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户密码不能为空"); md.showDialog(); } } } else if(select==2) { RegisterFrame rf=new RegisterFrame(LoginFrame.this); rf.showWindow(); } } } public boolean query(String userName,String userPsd) { Connection conn=null; PreparedStatement psm=null; ResultSet rs=null; String sql="select * from user_manager where name=? and psd=?"; boolean result=false; try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xdf","scott","tiger"); psm=conn.prepareStatement(sql); psm.setString(1,userName); psm.setString(2,userPsd); rs=psm.executeQuery(); //rs结果集指向第一条记录的前一个位置 //如果第一条记录为空表示用户名或密码错误 if(rs.next()==true) { result=true; this.closeWindow(); } psm.close(); conn.close(); } catch(ClassNotFoundException e1){ e1.printStackTrace(); } catch(SQLException e2){ e2.printStackTrace(); } catch(Exception e3){ e3.printStackTrace(); } return result; } } package com.nio.client; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import com.nio.user.ClientUser; import com.nio.user.ClientUserManager; import com.nio.user.UserData; public class NIOClient { private ClientUserManager cltManager = null; //通道管理器 private Selector selector; /** * 获得一个Socket通道,并对该通道做一些初始化的工作 * @param ip 连接的服务器的ip * @param port 连接的服务器的端口号 * @throws IOException */ public void initClient(String ip,int port) throws IOException { cltManager = ClientUserManager.instance(); // 获得一个Socket通道 SocketChannel channel = SocketChannel.open(); // 设置通道为非阻塞 channel.configureBlocking(false); // 获得一个通道管理器 this.selector = Selector.open(); // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调 //用channel.finishConnect();才能完成连接 channel.connect(new InetSocketAddress(ip,port)); //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。 channel.register(selector, SelectionKey.OP_CONNECT); } /** * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * @throws IOException * @throws InterruptedException */ @SuppressWarnings("unchecked") public void listen() throws IOException, InterruptedException { // 轮询访问selector while (true) { // 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞, //这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时, //selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的 selector.select(); // 获得selector中选中的项的迭代器 Iterator ite = this.selector.selectedKeys().iterator(); while (ite.hasNext()) { SelectionKey key = (SelectionKey) ite.next(); // 连接事件发生 if (key.isConnectable()) { SocketChannel channel = (SocketChannel) key .channel(); System.out.println("channel client ?" + channel); // 如果正在连接,则完成连接 if(channel.isConnectionPending()){ channel.finishConnect(); } //设置成非阻塞 channel.configureBlocking(false); //在这里可以给服务端发送信息哦 //channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes())); //在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。 channel.register(this.selector, SelectionKey.OP_READ); //添加用户 UserData userData = new UserData(); userData.lineState = 1; userData.channel = channel; cltManager.addUser(userData); //连接成功发送一个通知消息 UIClient.sendUserInfoMsg(); } else if (key.isReadable()) { ClientUser cltUser = cltManager.getUser((SocketChannel)key.channel()); if (!cltUser.read()) { key.channel().close(); } } //删除已选的key,以防重复处理 ite.remove(); } } } } package com.nio.server; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import com.nio.user.ServerUser; import com.nio.user.ServerUserManager; import com.nio.user.UserData; import com.ui.server.BootEndInterface; import com.ui.server.ServerBootFrame; public class NIOServer implements BootEndInterface { private ServerBootFrame serverFrame = new ServerBootFrame("服务器端"); private ServerUserManager userManager = null; HashMap hmClient = new HashMap(); Vector client = new Vector(); int count = 0; private static NIOServer nioServer = null; public NIOServer() { serverFrame.showFrame(); serverFrame.bootingServer(this); serverFrame.endingServer(this); serverFrame.closeWindow(this); nioServer = this; } // 通道管理器 private Selector selector; /** * 获得一个ServerSocket通道,并对该通道做一些初始化的工作 * * @param port * 绑定的端口号 * @throws IOException */ public void initServer(int port) throws IOException { serverFrame.appendStringTojtaState("服务器(NIO机制)启动中......\n"); // 获得一个ServerSocket通道 ServerSocketChannel serverChannel = ServerSocketChannel.open(); // 设置通道为非阻塞 serverChannel.configureBlocking(false); // 将该通道对应的ServerSocket绑定到port端口 serverChannel.socket().bind(new InetSocketAddress(port)); // 获得一个通道管理器 this.selector = Selector.open(); // 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后, // 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。 serverChannel.register(selector, SelectionKey.OP_ACCEPT); //System.out.println("serverChannel 0?" + serverChannel); } /** * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * * @throws IOException */ @SuppressWarnings("unchecked") public void listen() throws IOException { // System.out.println("服务端启动成功!"); serverFrame.appendStringTojtaState("服务器(NIO机制)启动成功......\n"); // 轮询访问selector while (true) { // 当注册的事件到达时,方法返回;否则,该方法会一直阻塞 selector.select(); // 获得selector中选中的项的迭代器,选中的项为注册的事件 Iterator ite = this.selector.selectedKeys().iterator(); while (ite.hasNext()) { SelectionKey key = (SelectionKey) ite.next(); // 客户端请求连接事件 if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key .channel(); // 获得和客户端连接的通道 SocketChannel channel = server.accept(); System.out.println("channel A?" + channel); // 设置成非阻塞 channel.configureBlocking(false); // 在这里可以给客户端发送信息哦 // channel.write(ByteBuffer.wrap(new // String("向客户端发送了一条信息").getBytes())); // 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。 channel.register(this.selector, SelectionKey.OP_READ); // 添加一个玩家对象 UserData userData = new UserData(); userData.lineState = 1; userData.channel = channel; userManager.addUser(userData); } else if (key.isReadable()) { ServerUser serverUser = userManager .getUser((SocketChannel) key.channel()); // 读取数据失败 if (!serverUser.read()) { serverUser.clean(); key.channel().close(); } } // 删除已选的key,以防重复处理 ite.remove(); } } } /** * 启动服务端测试 * * @throws IOException */ public static void main(String[] args) throws IOException { new NIOServer(); } @Override public void boot() { userManager = ServerUserManager.instance(); userManager.initUsers(); serverFrame.appendStringTojtaState("创建玩家内存数据对象成功...\n"); new Thread(new Runnable() { @Override public void run() { try { NIOServer.this.initServer(5555); NIOServer.this.listen(); } catch (Exception e) { serverFrame.appendStringTojtaState("服务器启动失败......\n"); } } }).start(); //服务端主逻辑处理 new Thread(new Runnable() { @Override public void run() { try { while (true) { Thread.sleep(1); userManager.run(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } @Override public void end() { if (selector != null) { try { selector.close(); selector = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.exit(0); } public void solveMsg(String message) { try { System.out.println(message); // 对消息进行分析 String msg[] = message.split("#"); if (msg[0].equals("AddUser") == true) { hmClient.put(msg[1], msg[2]); sendUsersToOneUser(msg[1]); if (likeThisName(msg[1]))// 如果出现同名用户,则在用户名后面添加数字来区分 { msg[1] = msg[1] + count; } client.add(msg[1]); serverFrame.appendStringTojtaState(msg[1] + "上线...\n"); sendMessageToAllUsers( "AddUser" + "#" + msg[1] + "#" + hmClient.get(msg[1]), msg[1]); } else if (msg[0].equals("UserQuit") == true) { sendMessageToAllUsers("UserQuit" + "#" + msg[1] + "#" + hmClient.get(msg[1]), msg[1]); serverFrame.appendStringTojtaState(msg[1] + "离线...\n"); deleteKeyValue(msg[1]); client.remove(msg[1]); // 应该删除vecUser容器中的对应的Socket对象 } else if (msg[0].equals("Message") == true) { // 如果将消息发送给特定用户 if (msg[1].equals("One") == true) { sendMessageToOneUser("Message" + "#" + msg[2] + "#" + msg[6], msg[4]); } else// 将消息发送给全部用户 { sendMessageToAllUsers("Message" + "#" + msg[2] + "#" + msg[4], msg[2]); } } } catch (Exception e) { e.printStackTrace(); } } public void sendMessageToAllUsers(String msg, String notSendToThisUserName) throws UnsupportedEncodingException { ServerUser lstUsers[] = userManager.getUsers(); for (int i = 0; i < lstUsers.length; i++) { if (lstUsers[i].channel != null) { String address = lockOut("" + lstUsers[i].channel.socket().getRemoteSocketAddress()); if ( !address.equals(hmClient.get(notSendToThisUserName)) ) { lstUsers[i].write(msg.getBytes("utf-8")); } } } } public void sendMessageToOneUser(String msg, String sendToThisUserName) throws UnsupportedEncodingException { ServerUser lstUsers[] = userManager.getUsers(); for (int i = 0; i < lstUsers.length; i++) { if (lstUsers[i].channel != null) { String address = lockOut("" + lstUsers[i].channel.socket().getRemoteSocketAddress()); if ( address.equals(hmClient.get(sendToThisUserName)) ) { lstUsers[i].write(msg.getBytes("utf-8")); break; } } } } // 方法完成将在线用户添给用户的下拉表中 public void sendUsersToOneUser(String newUserName) throws UnsupportedEncodingException { Iterator it = client.listIterator(); for (; it.hasNext();) { String name = it.next(); String ipAndPort = hmClient.get(name); sendMessageToOneUser("OnlyAddUser" + "#" + name + "#" + ipAndPort, newUserName); } } // 将键值对添加到hmClient哈希表中 public void createKeyValue(String userName, String socketAddress) { hmClient.put(userName, socketAddress); } // 从哈希表中删除指定键值对(键为:userName); public void deleteKeyValue(String userName) { hmClient.remove(userName); } // 将字符串前面的斜杠去掉 public String lockOut(String socketAddress) { return socketAddress.substring(1, socketAddress.length()); } // 如果client容器中存放的用户名出现相似用户,则用户名后面添加一个数字 public boolean likeThisName(String thisName) { count = 0; for (Iterator it = client.listIterator(); it.hasNext();) { String temp = (String) it.next(); if (temp.startsWith(thisName) == true) { count++; } } if (count > 0) return true; else return false; } public static void handleMessage(String msg) { // System.out.println("服务端收到信息:" + msg); nioServer.solveMsg(msg); } }
附登陆代码: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace 图书馆管理信息系统 { /// /// Form1 的摘要说明。 /// public class login : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.TextBox userid; private System.Data.SqlClient.SqlConnection sqlConnection1; private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; private System.Data.SqlClient.SqlCommand sqlSelectCommand1; private System.Data.SqlClient.SqlCommand sqlInsertCommand1; private System.Data.SqlClient.SqlCommand sqlUpdateCommand1; private System.Data.SqlClient.SqlCommand sqlDeleteCommand1; private 图书馆管理信息系统.DataSet1 dataSet11; private System.Windows.Forms.TextBox textboxpass; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public login() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(login)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label();
设置窗体的代码解释 Imports System.Diagnostics Public Class 设置窗体 Private shutTime As String '关机时间的字符串 Private IsToday As Boolean = True '判断是否是今天的变量 Private delay As Integer '延时多少秒放关机 Private lastTime As Integer '关机的倒计时 Private action As String '关机或重启或注销 Private shellText As String '执行的命令字符串 Private firstShow As Boolean = True Private SysTime As Boolean = False Private autoHide As Boolean = True '启动自动隐藏 Private TotalData As New System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Total/sec", "MS TCP Loopback interface") Private proTime As New System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total") '双击右下角的图标的响应事件 Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick If (Me.Visible = False) Then Me.Show() End If End Sub '重载窗体的关闭事件,使窗体隐藏 Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing e.Cancel = True '取消窗体的关闭动作 delayTime.Value = delay '还原delayTime控件的值 StrToItems() '还原ListBox的值 Me.Hide() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ComboBox1.SelectedIndex = 2 '设置默认选项 "每天" ComboBox2.SelectedIndex = 4 '设置默认选项 "关机" Timer1.Start() readReg() '读取存放在注册表的信息 StrToItems() '把字符串的信息读取到ListBox delayTime.Value = delay '把延时时间读取到delayTime控件 DateTimePicker1.Value = Today End Sub Private Sub 退出程序ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 退出程序ToolStripMenuItem.Click Me.Dispose() End Sub Private Sub 立即取消关机ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即取消关机ToolStripMenuItem1.Click Timer2.Stop() 取消窗体.Close() Shell("shutdown -a") Timer1.Start() End Sub Private Sub 设置关机计划ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 设置关机计划ToolStripMenuItem.Click If Me.Visible = False Then Me.Show() End If End Sub '点击确定按钮的事件处理 Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click '判断是否要开机自动运行 If autoCheck.Checked Then 创建开机自动运行() Else 删除开机自动运行() End If If Me.HideCheck.Checked Then autoHide = True Else autoHide = False End If If Me.regCheck.Checked Then 禁止修改注册表() Else 取消禁止修改注册表() End If If Me.ManCheck.Checked Then 禁止使用任务管理器() Else 取消禁止使用任务管理器() End If If Me.SysTimeCheck.Checked Then SysTime = True Else SysTime = False End If '四舍五入delayTime控件的值 delay = Math.Round(delayTime.Value, MidpointRounding.AwayFromZero) Me.Hide() ItemsToStr() '把listBox的信息保存到字符串中 writeReg() '把字符串保存把注册表中 End Sub '取消按钮事件 Private Sub canelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles canelButton.Click StrToItems() '还原ListBox的值 delayTime.Value = delay '还原delayTime控件的值 Me.Hide() End Sub '点击添加按钮 Private Sub addButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addButton.Click Dim tempStr As String = "" If ComboBox1.Items.Item(ComboBox1.SelectedIndex) = "指定日期" Then tempStr = DateTimePicker1.Value.ToShortDateString Else tempStr = ComboBox1.SelectedItem End If tempStr &= "," & CStr(Math.Round(hourNum.Value, MidpointRounding.AwayFromZero)) & ":" & CStr(Math.Round(minNum.Value, MidpointRounding.AwayFromZero)) & ":" & CStr(Math.Round(secNum.Value, MidpointRounding.AwayFromZero)) & "," Select Case ComboBox2.SelectedItem Case "打开网址" tempStr &= "打开网址" & "[" & TextBox1.Text.Replace(";", ";").Replace(":", ":") & "]" Case "提醒信息" tempStr &= "提醒信息" & "[" & TextBox1.Text.Replace(";", ";").Replace(":", ":") & "]" Case "打开文件" tempStr &= "打开文件" & "[" & TextBox1.Text.Replace(";", ";").Replace(":", ":") & "]" Case Else tempStr &= ComboBox2.SelectedItem End Select ListBox1.Items.Add(tempStr) End Sub '点击清除按钮 Private Sub clearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearButton.Click ListBox1.Items.Clear() End Sub '把ListBox的值保存到字符串ShutTime Private Sub ItemsToStr() Dim i As Integer shutTime = "" For i = 0 To ListBox1.Items.Count - 1 '把ListBox中的各项连接到shutTime shutTime &= ListBox1.Items.Item(i) & ";" Next If shutTime "" Then '去除最后一个 ";" shutTime = Mid(shutTime, 1, shutTime.Length - 1) End If End Sub '把字符串ShutTime的值还原到ListBox Private Sub StrToItems() If shutTime "" Then '如果shutTime有保存信息 Dim temp() As String = shutTime.Split(";") 'temp字符串数组存放shutTime以";"分隔的各个字符子串 Dim t As String 't存放temp字符串数组的一项 ListBox1.Items.Clear() For Each t In temp If Not (Mid(t, 1, 2) = "今天" And Not IsToday) Then '如果今天还没过了 ListBox1.Items.Add(t) End If Next End If End Sub '读取注册表保存的信息 Private Sub readReg() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey Try key = Microsoft.Win32.Registry.LocalMachine subkey = key.OpenSubKey("SOFTWARE\AutoShutdown") shutTime = subkey.GetValue("time") delay = CInt(subkey.GetValue("delayTime")) autoHide = subkey.GetValue("autoHide") If (CStr(Today()) subkey.GetValue("day")) Then IsToday = False End If Catch ex As Exception shutTime = "" IsToday = True End Try End Sub Private Sub 禁止修改注册表() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser subkey = key.CreateSubKey("software\microsoft\windows\currentversion\policies\system") subkey.SetValue("disableregistrytools", 1) End Sub Private Sub 取消禁止修改注册表() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser subkey = key.CreateSubKey("software\microsoft\windows\currentversion\policies\system") subkey.SetValue("disableregistrytools", 0) End Sub Private Sub 禁止使用任务管理器() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser subkey = key.CreateSubKey("software\microsoft\windows\currentversion\policies\system") subkey.SetValue("DisableTaskMgr", 1) End Sub Private Sub 取消禁止使用任务管理器() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser subkey = key.CreateSubKey("software\microsoft\windows\currentversion\policies\system") subkey.SetValue("DisableTaskMgr", 0) End Sub '将需要保存的信息写入注册表 Private Sub writeReg() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine subkey = key.CreateSubKey("SOFTWARE\AutoShutdown") subkey.SetValue("time", shutTime) subkey.SetValue("day", CStr(Today())) subkey.SetValue("delayTime", CStr(delay)) subkey.SetValue("autoHide", autoHide) End Sub '点击删除按钮 Private Sub delButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delButton.Click Dim delIndex As Integer = ListBox1.SelectedIndex If delIndex -1 Then ListBox1.Items.RemoveAt(delIndex) End If End Sub '最小化窗体,这里指隐藏窗体 Private Sub 最小化ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 最小化ToolStripMenuItem.Click If Me.Visible = True Then StrToItems() delayTime.Value = delay Me.Hide() End If End Sub Private Sub 创建开机自动运行() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine subkey = key.CreateSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run") subkey.SetValue("定时自动关机", Application.ExecutablePath) End Sub Private Sub 删除开机自动运行() Dim key As Microsoft.Win32.RegistryKey, subkey As Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine subkey = key.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True) subkey.DeleteValue("定时自动关机") End Sub '关闭显示器 Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer Public Const WM_SYSCOMMAND = &H112 Public Const SC_MONITORPOWER = &HF170 '关闭显示器 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long 'Timer1的Tick事件,来监视现在的时间是否应该关机或别的了 Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick Static nowTime As Date = Now updataMsg() If SysTime Then If (Now nowTime) Then Today = nowTime TimeOfDay = nowTime End If End If nowTime = nowTime.AddSeconds(1) If (shutTime "") Then Dim temp1() As String = shutTime.Split(";") 'temp1字符串数组存放shutTime以";"分隔的各个字符子串 Dim temp2() As String, i As Integer 'temp2字符串数组存放temp1某项的字符串以","或":"分隔的字符子串 Dim TimeOut As Boolean = False 'TimeOut存放是否时间到了 For i = 0 To temp1.Length - 1 temp2 = temp1(i).Split(New Char() {",", ":"}) If IsTimeOut(temp2) Then '判断时间是否到了 TimeOut = True action = temp2(4) '是"关机","注销","重启" End If Next If TimeOut Then '如果时间到 Select Case Mid(action, 1, 4) '根据action肯定命令字符串 Case "关闭计算" shellText = "shutdown -s -f -t 0" Case "重启计算" shellText = "shutdown -r -f -t 0" Case "注销用户" shellText = "shutdown -l -f -t 0" Case "关闭显示" SendMessage(Me.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 1) Exit Sub Case "锁定计算" shellText = "rundll32.exe user32.dll, LockWorkStation" Case "打开文件" System.Diagnostics.Process.Start(Mid(action, 6, action.Length - 6).Replace(":", ":")) Exit Sub Case "提醒信息" MsgBox(Mid(action, 6, action.Length - 6), , "提醒信息") Exit Sub Case "打开网址" System.Diagnostics.Process.Start(Mid(action, 6, action.Length - 6).Replace(":", ":")) Exit Sub End Select lastTime = delay '倒计时等于延时 Timer2.Start() '倒计时开始 取消窗体.Show() '倒计时窗口打开 Timer1.Stop() End If End If End Sub '判断时间是否到了 Private Function IsTimeOut(ByRef t() As String) As Boolean '如果时分秒都相等 If t(1) = CStr(Hour(Now())) And t(2) = CStr(Minute(Now()) And t(3) = Second(Now)) Then Select Case t(0) Case "每天" Return True Case "今天" Return True Case "每周二" If Weekday(Now) = FirstDayOfWeek.Tuesday Then Return True End If Case "每周六" If Weekday(Now) = FirstDayOfWeek.Saturday Then Return True End If Case "每周日" If Weekday(Now) = FirstDayOfWeek.Sunday Then Return True End If Case "每周三" If Weekday(Now) = FirstDayOfWeek.Wednesday Then Return True End If Case "每周四" If Weekday(Now) = FirstDayOfWeek.Thursday Then Return True End If Case "每周五" If Weekday(Now) = FirstDayOfWeek.Friday Then Return True End If Case "每周一" If Weekday(Now) = FirstDayOfWeek.Monday Then Return True End If Case "每周一至周五" If Weekday(Now) > FirstDayOfWeek.Sunday And Weekday(Now) < FirstDayOfWeek.Saturday Then Return True End If Case Else If (t(0) = Today.ToShortDateString) Then Return True End If End Select End If Return False End Function '刷新Msg控件 Private Sub updataMsg() Dim xingqi As String = "" Select Case Weekday(Now) Case 1 xingqi = "星期天" Case 2 xingqi = "星期一" Case 3 xingqi = "星期二" Case 4 xingqi = "星期三" Case 5 xingqi = "星期四" Case 6 xingqi = "星期五" Case 7 xingqi = "星期六" End Select msg.Text = "当前时间" & Now().ToLongDateString & " " & Now().ToLongTimeString & " " & xingqi & " CPU使用" & Format(proTime.NextValue, "#0") & "% 网速" & Format(TotalData.NextValue / 1024, "########0.00") & "KB/S" Me.NotifyIcon1.Text = msg.Text End Sub '倒计时处理事件 Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick If lastTime = 0 Then '如果时间到 Shell(shellText, AppWinStyle.Hide) 取消窗体.Label1.Text = "正在" & action Else 取消窗体.Label1.Text = "离" & action & "还有" & lastTime & "秒" '显示倒计时 lastTime -= 1 End If End Sub Private Sub 设置窗体_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown If autoHide Then Me.Hide() End If End Sub Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged Select Case ComboBox2.SelectedItem Case "打开网址" Button1.Visible = False TextBox1.Width = 299 TextBox1.Visible = True Case "提醒信息" Button1.Visible = False TextBox1.Width = 299 TextBox1.Visible = True Case "打开文件" Button1.Visible = True TextBox1.Width = 209 TextBox1.Visible = True Case Else Button1.Visible = False TextBox1.Visible = False End Select End Sub Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged If ComboBox1.SelectedItem = "指定日期" Then DateTimePicker1.Visible = True Else DateTimePicker1.Visible = False End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then TextBox1.Text = OpenFileDialog1.FileName End If End Sub Private Sub 立即关机ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即关机ToolStripMenuItem.Click Shell("shutdown -s -f -t 0") End Sub Private Sub 立即重启ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即重启ToolStripMenuItem.Click Shell("shutdown -r -f -t 0") End Sub Private Sub 立即注销ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即注销ToolStripMenuItem.Click Shell("shutdown -l -f -t 0") End Sub Private Sub 立即锁定计算机ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即锁定计算机ToolStripMenuItem.Click Shell("rundll32.exe user32.dll, LockWorkStation") End Sub Private Sub 立即关闭显示器ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 立即关闭显示器ToolStripMenuItem.Click SendMessage(Me.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 1) End Sub Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked System.Diagnostics.Process.Start("http://lywang.5d6d.com/space-uid-1.html") End Sub End Class

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧