总有记录:21条,共3页 总有记录:21条,共3页 1 2 3 总有记录:21条,共3页 总有记录:21条,共3页,点这里转到尾页

您可以按 列表 | 普通 浏览

C# COM 口通讯

[ 2008-6-3 18:41:55 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

public class ComPort
{

static bool _continue;

static SerialPort _serialPort;

public static void Main(string[] args)

{

string name;

string message;

StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;

Thread readThread = new Thread(Read);

// Create a new SerialPort object with default settings.

_serialPort = new SerialPort();

// Allow the user to set the appropriate properties.

_serialPort.PortName = SetPortName(_serialPort.PortName);

_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);

_serialPort.Parity = SetPortParity(_serialPort.Parity);

_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);

_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);

_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

// Set the read/write timeouts

_serialPort.ReadTimeout = 500;

_serialPort.WriteTimeout = 500;

_serialPort.Open();

_continue = true;

readThread.Start();

Console.Write("Name: ");

name = Console.ReadLine();

Console.WriteLine("Type QUIT to exit");

while (_continue)

{

message = Console.ReadLine();

if (stringComparer.Equals("quit", message))

{

_continue = false;

}

else

{

_serialPort.WriteLine(

String.Format("<{0}>: {1}", name, message));

}

}

readThread.Join();

_serialPort.Close();

}

public static void Read()

{

while (_continue)

{

try

{

string message = _serialPort.ReadLine();

Console.WriteLine(mes

分类:.NET | 部落: | 评论:0 | 阅读全文(59)

(C#)在.NET 2.0 中使用 BackgroundWorker 组件

[ 2008-6-3 18:41:16 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

在.NET 2.0 中使用 BackgroundWorker 组件
在WinForm中经常遇到一些费时的操作界面,比如统计某个磁盘分区的文件夹或者文件数目,如果分区很大或者文件过多的话,处理不好就会造成“假死”的情况,或者报“线程间操作无效”的异常,为了解决这个问题,可以使用委托来处理,在.net2.0中还可以用BackgroundWorker类。

BackgroundWorker可以让窗体异步地完成一个操作。在我们需要执行诸如『数据库事务』或者『图片下载』之类的操作时,这个功能非常有用。此时,我们的可以让用户界面停止响应(或者隐藏起来直到操作结束)。在这篇文章中,我会一步一步教会你如何在.NET 2.0程序中使用BackgroundWorker组件以便处理较耗时的操作。示例程序使用C#编写。
与往常一样,我们创建一个测试工程,取名为"TestBGW",使之只包含一个窗体("FormBGW"):

图1.
我们将使用BackgroundWorker完成一些数据库的事务操作(比如,获取一些DataTable)。首先拖一个BackgroundWorker组件到我们窗体上。

图2.
我们将用DataTable来设置DataGridView1的DataSource属性。我们还应该刷新我们的用户界面,并告诉用户:所有的操作已经全部“OK”,他/她不用再操心啦。因此,我们还要需要一个StatusStrip和一个Timer.

图3.
为了让用户看到我们的处理过程正在运行之中,我们将用到toolStripProgressBar1:

图4.
用toolStripStatusLabel1和toolStripStatusLabelTime是来向用户显示处理过程的状态和已经花费的时间。
我们窗体看上去是这样子的:


图5.
为了模拟数据库的事务操作,我们将用到GetData.dll(当然你也可以连接到一个真实的数据库;这个模拟的目的只是为了测试而已)。出于这个目的,我们把GetData.dll添加到引用中,然后写因getDataTable方法:

private DataTable getDataTable(int Rows)
{

GetData.GetDataHelp getData = new GetData.GetDataHelp();

return (getData.getDataSetCities(Rows).Tables[0]);

}


我们调用RunWokerAsync方法开始我们的异步操作:


private void FormBGW_Activated(object sender, EventArgs e)
{

backgroundWorker1.RunWorkerAsync();

}


BackGroundWorker组件有三个事件:

图6.


DoWork事件发生在RunWokerAsync方法被调用时。在这个事件的处理函数中,我们“完成”那些的耗时的工作(我们载入至少100000行数据以便使我们的处理过程变得“耗时”),并通知用户载入工作正在进行中,最后将我们的DataTable置为我们的异步操作的结果。


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

DataTable dt;

toolStripStatusLabel1.Text = "Loading ... " + "Thanks for your patience";

dt = getDataTable(1000000);

e.Result = dt;

}


就我们面对的情况而言(我是指真实的情况,即从数据库获得一些DataTable的情况),我们没办法“插入”处理过程以“追踪”已获取的数据行数量(一行接一行)。当然,我们同样也没有办法知道,根据我们的请求最终可以从数据库获得多少数据行。所以呢,我们不会用DoWorkEventArgs(译注:应为BackgroudWorker的笔误)的ReportProgress 方法来触发ProgressChanged事件。我们将用Timer1,向用户显示处理过程正在进行中(我们将把 toolStripProgressBar1“增加”到最大程度,然后再从最短长度继续开始;就是说,我们会制造一些循环)。因此我们给 timer1_Tick加上下面的代码:

分类:.NET | 部落: | 评论:0 | 阅读全文(83)

C# MD5,SHA1加密

[ 2008-6-3 18:40:27 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

C# MD5,SHA1加密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication5
{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("请输入待加密的内容:");

Console.WriteLine();

string strSrc = Console.ReadLine().ToString();

Console.WriteLine();

Console.WriteLine("你输入的内容是:" + strSrc);

Console.WriteLine();

Console.WriteLine("MD5加密后编码:" + MD5_Hash(strSrc));

Console.WriteLine();

Console.WriteLine("SHA1加密后编码:" + SHA1_Hash(strSrc));

Console.WriteLine();

Console.ReadLine();

//Console.WriteLine("MD5加密后编码:" + UserMd5("16"));

//Console.WriteLine();

//Console.WriteLine("SHA1加密后编码:" + cncrypto(strSrc));

//Console.WriteLine();

//Console.WriteLine(Ge***5Str("8"));

}

//MD5

static public string MD5_Hash(string str_md5_in)

{

MD5 md5 = new MD5CryptoServiceProvider();

byte[] bytes_md5_in = UTF8Encoding.Default.GetBytes(str_md5_in);

byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in);

string str_md5_out = BitConverter.ToString(bytes_md5_out);

str_md5_out = str_md5_out.Replace("-", "");

return str_md5_out;

}

//SHA1

static public string SHA1_Hash(string str_sha1_in)

{

SHA1 sha1 = new SHA1CryptoServiceProvider();

byte[] bytes_sha1_in = UTF8Encoding.Default.GetBytes(str_sha1_in);

byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);

string str_sha1_out = BitConverter.ToString(bytes_sha1_out);

str_sha1_out = str_sha1_out.Replace("-", "");

return str_sha1_out;

}

//static public string cncrypto(str

分类:.NET | 部落: | 评论:0 | 阅读全文(73)

C#:从DataGridView控件托放数据到TreeView控件

[ 2008-6-3 18:39:53 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

C#:从DataGridView控件托放数据到TreeView控件
在datagridview的mousedown事件中开始 托放。
然后在treeview 的 DragEnter 中接收托放。
最后在treeview的 DragDrop 中处理托放结果。
注:treeview的allowdrop属性要设置为 true。

1

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)

2

{

3

if (e.Button == MouseButtons.Right)

4

{

5

DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y);

6

7

if (info.RowIndex >= 0)

8

{

9

DataGridViewRow dr = (DataGridViewRow)

10

dataGridView1.Rows[info.RowIndex];

11

if (dr != null)

12

dataGridView1.DoDragDrop(dr, DragDropEffects.Copy);

13

}

14

}

15

}

16
17

private void treeView1_DragEnter(object sender, DragEventArgs e)

18

{

19

e.Effect = DragDropEffects.Copy;

20

}

21
22

private void treeView1_DragDrop(object sender, DragEventArgs e)

23

{

24

if (e.Data.GetDataPresent(typeof(DataGridViewRow)))

25 {

26

Point p = treeView1.PointToClient(new Point(e.X, e.Y));

27

TreeViewHitTestInfo index = treeView1.HitTest(p);

28
29

if (index.Node != null)

30

{

31
32

DataGridViewRow drv = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));

33

index.Node.Text = "Drop: " + drv.Cells[0].ToString();

34

35

}

36

}

37

}

分类:.NET | 部落: | 评论:0 | 阅读全文(69)

c#用回车键实现TAB功能

[ 2008-6-3 18:38:19 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

c#用回车键实现TAB功能
方法:把Form的KeyPreView设为true,然后在Form的KeyPress事件中增加下列代码即可:

if (e.KeyChar == '\r')

this.SelectNextControl(this.ActiveControl, true, true, true, true);

这个方法我认为最简洁.

分类:.NET | 部落: | 评论:0 | 阅读全文(62)

符合web标准的嵌入Flash的方法

[ 2008-6-3 18:37:47 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

符合web标准的嵌入Flash的方法
如何让网页中嵌入的Flash标签也符合web标准。目前还没有一个完美的解决办法,这篇文章中,我们将Flash嵌入标签写入js文件中,通过变量传递参数的办法来回避不符合标准的标签。

  请注意,这只是一个变通的方法,换汤不换药,并未能最终解决存在的问题,通过验证只是一种表象,这样的思路是不是可取,在实际操作中请大家自行斟酌。
  首先建立一个JS文件flash.js。写入如下代码:
function swf(file,w,h) {

document.write('&lt;object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="<a target="_blank" rel="nofollow" href="http://download.Macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7">http://download.Macromedia.com/pub/sho ... h/swflash.cab#version=7</a>,0,19,0" width="'+w+'" height="'+h+'"&gt; ');

document.write('&lt;param name="movIE" value="' + file + '"&gt;');

document.write('&lt;param name="quality" value="high"&gt; ');

document.write('&lt;param name="wmode" value="transparent"&gt; ');

document.write('&lt;param name="menu" value="false"&gt; ');

document.write('&lt;embed src="' + file + '" quality="high" pluginspage="<a target="_blank" rel="nofollow" href="http://www.macromedia.com/go/getflashplayer">http://www.macromedia.com/go/getflashplayer</a>" type="application/x-shockwave-flash" width="'+w+'" height="'+h+'"&gt;&lt;/embed&gt; ');

document.write('&lt;/object&gt; ');

}
  上面的js脚本定义了一个函数swf,并设置三个变量,它们分别是:flile文件链接,w宽度,h高度。在XHTML中向这个函数传递变量即可实现flash的嵌入。如下代码:
<div id="flash">

&lt;script type="text/<i>&#106avascript</i>" language="<i>&#106avascript</i>"&gt;swf('filename.swf','500','220');&lt;/script&gt;

</div>

  建立id为flash的div作为一容器,在其内部嵌入js脚本,变量依次为:文件路径、宽度、高度。
  看下面的全部代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>符合web标准的嵌入Flash的方法</title>
<script type="text/javascript" language="javascript" src="flash.js"></script>
<style type="text/CSS">
#flash { width:500px; margin:50px auto; border:5px solid #03c;}
</style>
</head>
<body>
<div id="flash">

&lt;script type="text/<i>&#106avascript</i>" language="<i>&#106avascript</i>"&gt;swf('filename.swf','500','220');&lt;/script&gt;

</div>
</body>
</html>

分类:HTML&Javascript | 部落: | 评论:0 | 阅读全文(65)

C#使用OLEDB将EXCEL文件导入到SQL SERVER中

[ 2008-6-3 18:35:51 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

//****************使用OLEDB将EXCEL文件导入到SQL SERVER中。*******************

//private OleDbConnection m_XLSConn;

//private OleDbDataAdapter m_XLSAdapter;

//private DataTable GetDataFromXLS(string s_FileName)

//{

// string s_ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + s_FileName + ";Extended Properties = Excel 8.0";

// string s_SQLSelect = "select * from jx";

// m_XLSConn = new OleDbConnection(s_ConnString);

// m_XLSAdapter = new OleDbDataAdapter(s_SQLSelect, m_XLSConn);

// DataTable m_dtXLS = null;

// try

// {

// m_dtXLS = DataTable();

// m_XLSConn.Open();

// m_XLSAdapter.Fill(m_dtXLS);

// }

// catch (Exception exc)

// {

// throw exc;

// }

// finally

// {

// if (m_XLSConn.State == ConnectionState.Open)

// m_XLSConn.Close();

// }

// return m_dtXLS;

//}

private void simpleButton6_Click_1(object sender, EventArgs e)

{

try

{

int i;

string only;

SqlConnection conn = new SqlConnection("Data Source=172.16.112.20\\jweb;Initial Catalog=db_OA;Persist Security Info=True;User ID=sa;Password=");

only = "select count(*) from JobINcentive where 姓名 like '%" + cmbName.Text.Trim().ToString() + "%' and 日期='" + lblData.Text.Trim().ToString() + "'";

SqlCommand onlycmm = new SqlCommand(only, conn);

conn.Open();

i = (int)onlycmm.ExecuteScalar();

conn.Close();

if (lblData.Text == "" &#124;&#124; cmbName.Text == "" &#124;&#124; cmbName.Text == "--=请选择=--")

{

MessageBox.Show("日期和姓名必须填写,并且必须和将导入的报表中相同,否则将出现想现不到的结果,请慎重!", "导入条件不全", MessageBoxBu

分类:.NET | 部落: | 评论:0 | 阅读全文(80)

c#读写ini文件

[ 2008-6-3 18:35:20 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

//==================创建INI文件读写函数======================

//调用kernel32.dll中的两个API:WritePrivateProfileString,GetPrivateProfileString来实现对ini文件的读写

[DllImport("kernel32")]

private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

[DllImport("kernel32")]

private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

public void IniWriteValue(string Section, string Key, string Value, string filepath) //对ini文件进行写操作的函数

{

WritePrivateProfileString(Section, Key, Value, filepath);

}

public string IniReadValue(string Section, string Key, string filepath) //对ini文件进行读操作的函数

{

StringBuilder temp = new StringBuilder(255);

int i = GetPrivateProfileString(Section, Key, "", temp, 255, filepath);

return temp.ToString();

}

//==================开始写入INI文件操作====================

public void writeIniFileSqlServer()

{

//label13.Text = "";

string iniFile = "DBC.ini";

string iniFilePath = Application.StartupPath + "\\" + iniFile;

if (!System.IO.File.Exists(iniFilePath))

{

System.IO.File.CreateText(iniFilePath);

}

if (comboBox4.Text == "")

{

MessageBox.Show("请选择一种类型的数据库", "选择错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

else if (comboBox4.Text == "Sql Server")

{

try

{

IniWriteValue("OLEDB for Sql Server", "Microsoft Sql Server Database Sources",textBox4.Text + "\\" + textBox5.Text + ";Initial Catalog=" + textBox6.Text + ";Persist Security Info=True;User ID=" + textBox7.Text + ";Password=" + textBox8.Text, iniFilePath);

分类:默认分类 | 部落: | 评论:0 | 阅读全文(76)

给图片加水印jsp

[ 2008-6-3 18:34:36 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

package com.free;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.*;
public class WaterMark {

/**

* 给图片添加水印

* @param filePath 需要添加水印的图片的路径

* @param markContent 水印的文字

* @param markContentColor 水印文字的颜色

* @param qualNum 图片质量

* @return

*/

public boolean createMark(String filePath,String markContent,Color markContentColor,float qualNum)

{

//图片

ImageIcon imgIcon=new ImageIcon(filePath);

Image theImg =imgIcon.getImage();

int width=theImg.getWidth(null);

int height= theImg.getHeight(null);

BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);

//

水印图片

ImageIcon imgIcon1=new ImageIcon("f://ee.gif");

Image theImg1 =imgIcon1.getImage();

Graphics2D g=bimage.createGraphics();

g.setColor(markContentColor);

g.setBackground(Color.white);

g.drawImage(theImg, 0, 0, null );

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1f)); //添加图片水印

g.drawImage(theImg1,0,0,null);

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

//

g.drawString(markContent,width-200,height-10); //添加水印的文字和设置水印文字出现的内容 和位置

g.dispose();

try{

FileOutputStream out=new FileOutputStream(filePath);

JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);

encoder.encode(bimage);

out.close();

}catch(Exception e)

{ return false; }

return true;

}

public static void main(String[] args) {

WaterMark wm = new WaterMark();

if (wm.createMark("f://yy.jpg","&lt;h1&gt;<a target="_blank" rel="nofollow" href="http://www.free-120.com">http://www.free-120.com</a>&lt;h1&gt;",Color.RED,80f))

{

System.out.println("添加水印成功!");

}

else

{

System

分类:JSP | 部落: | 评论:0 | 阅读全文(53)

[C#]钩子拦截键盘输入

[ 2008-6-3 18:32:17 | 作者:18670409002兰锋 | 出处:原创 | 天气:晴 ]

钩子(Hook),是Windows消息处理机制的一个平台,应用程序可以在上面设置子程以****指定窗口的某种消息,而且所****的窗口可以是其他进程所创建的。当消息到达后,在目标窗口处理函数之前处理它。钩子机制允许应用程序截获处理window消息或特定事件。
可惜,.NET 目前不支持全局钩子,这是最最最郁闷的事情了。

internal enum HookType //枚举,钩子的类型

{

//MsgFilter = -1,

//JournalRecord = 0,

//JournalPlayback = 1,

Keyboard = 2,

//GetMessage = 3,

//CallWndProc = 4,

//CBT = 5,

//SysMsgFilter = 6,

//Mouse = 7,

//Hardware = 8,

//Debug = 9,

//Shell = 10,

//ForegroundIdle = 11,

//CallWndProcRet = 12,

//KeyboardLL = 13,

//MouseLL = 14,

};


IntPtr _nextHookPtr; //记录Hook编号


3、引入必须的API

[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId(); //取得当前线程编号的API


[DllImport("User32.dll")]

internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API


[DllImport("User32.dll")]

internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)]

HookProc lpfn, IntPtr hinstance, int threadID); //设置Hook的API


[DllImport("User32.dll")]

internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam);

//取得下一个Hook的API

4、声明一个实现的委托

internal delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);

5、添加自己的Hook处理过程


IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)

{

if( code < 0 ) return CallNextHookEx(_nextHookPtr,code, wparam, lparam);

//MSDN教育我们code小于0必须放行
//添加自己的处理动作
return (IntPtr)0;//如果默认对话框过程处理此消息,则为零值;如果默认对话框过程忽略此消息,则为非零值。

}


6、添加加入Hook链和从Hook链中取消的函数


public void SetHook()

{

if( _nextHookPtr != IntPtr.Zero ) //已经钩过了


return;


HookProc myhookProc = new HookProc(MyHookProc); //声明一个自己的Hook实现函数的委托对象


_nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc , IntPtr.Zero ,

GetCurrentThreadId()); //加到Hook链中

}


public void UnHook()

{

if( _nextHookPtr != IntPtr.Zero )

{

UnhookWindowsHookEx(_nextHookPtr); //从Hook链中取消


_nextHookPtr = IntPtr.Zero;

分类:.NET | 部落: | 评论:0 | 阅读全文(71)

总有记录:21条,共3页 总有记录:21条,共3页 1 2 3 总有记录:21条,共3页 总有记录:21条,共3页,点这里转到尾页

您可以按 列表 | 普通 浏览

导航

归档

日历

我的简历

  • 姓名:18670409002兰锋
  • 性别:男
  • 注册日期:
  • Email:rowlandlan@163.com
  • 城市:成都
  • 发消息给我

公告

欢迎光临我的博客!

部落

  • 没有加入任何部落!

最新回复

  • 没有任何评论

联接

统计

  • 访问人数:4213 人
  • 创建时间:2007-12-13
  • 发表文章:21 篇
  • 上传相片:0 张
  • 回复总数:0 篇
  • 阅读总数:1592 次
  • RSS订阅
  • mozilla firefox:支持WEB标准的最佳浏览器
  • 程序开发商:慈溪都市博客
  • 理论上本站符合XHTML标准,但由于用户输入日志的不确定性,可能会有几个错误通不过