存档

‘C#学习’ 分类的存档

在ppc上实现MessageBox自动消失

2010年5月5日

之所以有这篇文章,得首先感谢组员zhangjing同学,正是因为有了她的idea,我才会去寻找解决方案,希望我们组的成员能多多提出好的idea。实现MessageBox自动消失的类的源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class MessageBoxTimeOut
    {
        private string _caption;
 
        public void Show(string text, string caption, int timeout)
        {
            this._caption = caption;
            StartTimer(timeout);
            MessageBox.Show(text, caption);
        }
 
        private void StartTimer(int interval)
        {
            Timer timer = new Timer();
            timer.Interval = interval;
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Enabled = true;
        }
 
        private void Timer_Tick(object sender, EventArgs e)
        {
            KillMessageBox();
            //停止计时器
            ((Timer)sender).Enabled = false;
        }
 
        [DllImport("coredll.dll", EntryPoint = "FindWindow", 
                                       CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow
                  (string lpClassName, string lpWindowName);
 
        [DllImport("coredll.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, 
                                             IntPtr wParam, IntPtr lParam);
 
        public const int WM_CLOSE = 0x10;
 
        private void KillMessageBox()
        {
            //查找MessageBox的弹出窗口,注意对应标题
            IntPtr ptr = FindWindow(null, this._caption);
            if (ptr != IntPtr.Zero)
            {
                //查找到窗口则关闭
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
    }

C#学习, 移动平台

C#实现控件与窗体大小自适应

2009年12月28日

昨天,做RFID项目的时候,需要使得窗体中控件按照窗体大小来调整,从而达到视觉上的自适应效果。我的窗体大小是按照1024*768的分辨率来设置的,按照项目的要求窗体需要最大化显示,这时问题就出现了,控件大小及字体都按照原来的设置显示,窗体中就出现了空白的地方,而且有的控件错位显示。
我试着设置了控件的Dock与Anchor属性,但都无济于事,最后只能来循环设置控件的大小,从而使得布局美观。网上找了相关资料,最后自己整理写出了如下代码。
首先,在Form窗体中添加如下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
        private void setTag(Control cons)
        {
            //MessageBox.Show("setTag");
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0) {
                    //MessageBox.Show("ok");
                    setTag(con);
                }
 
            }
        }
        //调整每个控件的大小
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
 
                //MessageBox.Show(con.Tag.ToString());
                string[] mytag = con.Tag.ToString().Split(':');
                float a = Convert.ToSingle(mytag[0]) * newx;
                con.Width = (int)a;
                a = Convert.ToSingle(mytag[1]) * newy;
                con.Height = (int)(a);
                a = Convert.ToSingle(mytag[2]) * newx;
                con.Left = (int)(a);
                a = Convert.ToSingle(mytag[3]) * newy;
                con.Top = (int)(a);
                Single currentSize = Convert.ToSingle(mytag[4]) * newy;
                con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                {
                    setControls(newx, newy, con);
                }
            }
        }      
       //窗体大小自适应
        private void NewOrderDashForm_Resize(object sender, EventArgs e)
        {
            //MessageBox.Show("resize");
            // throw new Exception("The method or operation is not implemented.");            
            float newx = (this.Width) / X;            
            float newy = this.Height / Y;
            setControls(newx, newy, this);
            this.Text = this.Width.ToString() + " " + this.Height.ToString();
        }

添加Form_load事件,代码如下

1
2
3
4
5
            //窗体与控件的自适应
            this.Resize += new EventHandler(NewOrderDashForm_Resize);
            X = this.Width;
            Y = this.Height;
            setTag(this);

最后,别忘了声明变量X,Y,这样就可以实现控件大小与窗体的自适应了,也解决了我的一大问题,嘿嘿。

C#学习

C#播放Flash文件

2009年12月25日

简单的学习了一下C#播放flash文件,其原理是引用Flash的dll,用其来实现对Flash文件的播放。主要包括以下三个步骤:

第一,添加控件。

右击工具箱区域(接收sky的意见,做一下修改~)——选择项——COM组件——选择Shockwave Flash Object,点击确定。之后根据需要对该dll文件进行注册。注册方式为regsvr32 C:\Windows\System32\Macromed\Flash\Flash10a.ocx

第二,拖放控件至窗体。

拖放控件Flashwave Flash Object至窗体相应位置。

第三,添加代码。

添加代码的时候,只需要添加控件的两个属性即可,注意添加Movie属性的时候务必是绝对路径。

?Download flash.txt
1
2
         axShockwaveFlash1.Movie = "D:\\源码\\flash.swf";
         axShockwaveFlash1.Play();

C#学习

sql server ce的事务操作

2009年10月29日

前几天,在做RFID手持端开发时,发现若插入多条数据总不能成功执行,在仔细核对sql语句确认正确的基础上,我想应该是多条sql语句的错误。
在sqlce中进行数据库操作时,若有多条以“;”分隔的sql语句,则不能正确执行(在wince系统中如此,其他系统没有测试),这时一个比较好的解决方法,就是采用sqlce的事务机制。下面是一个比较简单的代码,在使用的时候可以加以修改以适合自己的需要。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    public void RunSqlCeTransaction(string myConnString) {
    SqlCeConnection myConnection = new SqlCeConnection(myConnString);
    myConnection.Open();
    SqlCeCommand myCommand = new SqlCeCommand();
    SqlCeTransaction myTrans;
    // Start a local transaction
    myTrans = myConnection.BeginTransaction();    
    // Must assign both transaction object and connection
    // to Command object for a pending local transaction
    myCommand.Connection = myConnection;
    myCommand.Transaction = myTrans;
    try {
        myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
        myCommand.ExecuteNonQuery();
        myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
        myCommand.ExecuteNonQuery();
        myTrans.Commit();
    }
    catch(Exception) {
        try {
            myTrans.Rollback();
        }
        catch (SqlCeException) {
            // Handle possible exception here
        }
    }
    finally {
        myConnection.Close();
    }
}

C#学习, 移动平台

TcpClient类和TcpListener类

2009年5月3日

        TcpClient类和TcpListener类属于.NET框架下网络通信中的应用层类,为Socket通信提供了更简单,对用户更为友好的接口。应用层类比位于底层的Socket类提供了更高层次的抽象,封装了套接字的创建,不需要处理连接的细节。

        TcpClient类以更高的抽象程度提供TCP服务的基础,因此许多应用层次上的通信协议,比如FTP传输协议、HTTP超文本传输协议都直接创建在TcpClient等类之上。TcpClient类直接为客户端设计,提供了通过网络连接发送和接收数据的简单方法;TcpListener类用于服务器端,用来监视TCP端口上客户端的请求。

1.TcpClient类

        要建立TCP连接,应该提供IP地址和端口号。TcpClient类有三种构造函数。

     (1)public TcpClient():使用本机默认的IP地址和默认的端口0来创建TCP连接。

     (2)public TcpClient(IPEndPoint):IPEndPoint指定在建立远程连接时所使用的本机IP地址和端口号。

     (3)public TcpClient(string,int):初始化TcpClient类的新实例,并连接到指定主机上的制定端口。

         需要说明的是,在使用前两种构造函数的时候,只是实现了TcpClient实例对象与IP地址和Port端口的绑定,要完成连接,还需要显示地用Connect方法指定与远程主机的连接。

         在网络数据接收和发送方面,TcpClient类使用NetworkStream网络流处理技术,使得读写数据更加方便直观,而不需考虑具体传输的内容。在使用GetStream方法获得用于发送和接收数据的网络流之后,就可以使用标准流读写方法Write和Read来发送和接收数据了。

2.TcpListener类

          TcpListener类用于监视TCP端口上客户端的请求,通过绑定本机IP地址和端口(IP地址和端口应与客户端请求一致)来创建TcpListener对象实例,由Start()方法启动侦听;当TcpListener侦听到客户端连接后,根据客户端的请求方式来处理请求,即如果是Socket连接请求,则使用AcceptSocket方法,如果是TcpClient连接请求,则使用AcceptTcpClient方法。最后要关闭使用的连接。

C#学习 , ,

同步模式下的流套接字Socket编程

2009年4月30日

本文介绍同步模式下的流套接字Socket编程,关于Socket通信的原理在前一篇文章中已经介绍了,在此就不多说了,仅以例子进行说明
Server端:接收数据,并显示,同时反馈给客户端信息,程序是多线程的

?Download PcSocket.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace test.socket
{
    class PcSocket
    {
        //private Socket server;
        private int SERVER_PORT=9696;//侦听端口
        private string SERVER_IP = "222.195.151.223";//服务器地址
        private static int BUFFER_SIZE = 65535;//设置缓冲区大小
        public PcSocket() {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipadd = IPAddress.Parse(SERVER_IP);            
            IPEndPoint ipe = new IPEndPoint(ipadd, SERVER_PORT);
            server.Bind(ipe);
            server.Listen(100);
            Console.WriteLine("wait for the client to build Connection……");
            while (true) {
                Socket client = server.Accept();//阻塞方法,创建新的连接
                ClientThread newClient = new ClientThread(client);//创建了ClientThread类的实例
                Thread newThread = new Thread(new ThreadStart(newClient.ClientServer));//新建线程,并将ClientThread类的实例的方法赋给线程
                newThread.Start();//启动线程
            }
 
        }
        class ClientThread {           
            private Socket client;
            private string data = null;
            private byte[] receiveBytes = new byte[BUFFER_SIZE];//服务器端设置缓冲区
            int i;
            private int bytesCount;
            public ClientThread(Socket ClientSocket) {
                this.client = ClientSocket;
            }
            public void ClientServer() {     
 
                try
                {
                    bytesCount = client.Receive(receiveBytes, receiveBytes.Length, 0);//从客户端接收信息
                    if (bytesCount != 0)//当服务器端的缓冲区接收到的信息不为空时
                    {
                        data = Encoding.ASCII.GetString(receiveBytes, 0, bytesCount);
                        Console.WriteLine("Receive date:{0}", data);
                        string sendStr = "OK!Client send message sucessfully";
                        byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
                        client.Send(sendBytes, sendBytes.Length, 0);//向客户端发送信息                        
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("出现异常:");
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                } 
                client.Close();               
            }
        }
    }
}

Client端:发送数据,并接收服务器端反馈的信息,进行显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace testClient.client
{
    class ClientSocket
    {
        private int SERVER_PORT = 9696;
        private string SERVER_IP = "222.195.151.223";
        private static int BUFFER_SIZE = 65535;
        private Socket client = null; //客户端套接字        
        private string clientInput; // 输入的字符串
        private string clientReceiveStr=null;//接收到的字符串
        private byte[] clientSendBytes = new byte[BUFFER_SIZE];
        private byte[] clientReceiveBytes = new byte[BUFFER_SIZE];
        public ClientSocket()
        {            
            try
            {      
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                
                IPAddress ipadd = IPAddress.Parse(SERVER_IP);
                IPEndPoint ipe = new IPEndPoint(ipadd, SERVER_PORT);                
                client.Connect(ipe);               
            }
            catch (SocketException se)
            {
                Console.WriteLine("服务器程序尚未启动!请先启动服务器程序!");
                Console.WriteLine("Error occurs:" + se.ToString());
                Console.ReadLine();
            }          
            if (client.Connected) //如果与服务器已经建立连接
            {
                try
                {                    
                    clientInput = "hello,this is a socket test";                    
                    clientSendBytes = Encoding.ASCII.GetBytes(clientInput);                    
                    //Send方法返回一个System.Int32类型的值,表明已发送数据的大小
                    client.Send(clientSendBytes, clientSendBytes.Length, 0);                    
                    int bytes = client.Receive(clientReceiveBytes, clientReceiveBytes.Length, 0);//从服务器端接受返回信息
                    clientReceiveStr = Encoding.ASCII.GetString(clientReceiveBytes, 0, bytes);
                    Console.WriteLine("client get message:{0}", clientReceiveStr);//显示服务器返回信息                   
                }
                catch (Exception ex)
                {
                    Console.Write("出现异常:");
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                }             
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                Console.ReadLine();
 
            }
 
        }
 
    }
}

C#学习, 移动平台 ,