整理下在公司的时候一些小技巧性代码
转眼间已经离开公司小半年了,这期间创业真实辛苦不少,天天起早贪黑的,真是累人,网店终于有了点小起色,能够养活自己了,但是如何做大,怎么做好,还有资金的问题,又是摆在面前的难关啊。。。
自己为了方便,偶尔写一些小软件,每次写的时候都发现手生了好多,很多东西以前用到过,但是就是想不起来,所以在这里做个整理吧,方便以后使用:
1 。全角半角转换
/// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>全角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public string ToSBC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary> 转半角的函数(DBC case) </summary>
/// <param name="input">任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
private string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>全角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public string ToSBC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary> 转半角的函数(DBC case) </summary>
/// <param name="input">任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
private string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
2。 过滤危险字符,防止SQL注入
/// <summary>
/// 过滤危险字符(防止Sql注入)
/// </summary>
/// <param name="contents">预检测的内容</param>
/// <returns>返回True或false</returns>
private bool HasDangerousContents(string contents)
{
bool bReturnValue = false;
if (contents.Length > 0)
{
//convert to lower
string sLowerStr = contents.ToLower();
//RegularExpressions
string sRxStr = @"(\sand\s)|(\sand\s)|(\slike\s)|(select\s)|(insert\s)|(delete\s)|(update\s[\s\S].*\sset)|(create\s)|(\stable)|(<[iframe|/iframe|script|/script])|(')|(\sexec)|(\sdeclare)|(\struncate)|(\smaster)|(\sbackup)|(\smid)|(\scount)";
//Match
bool bIsMatch = false;
System.Text.RegularExpressions.Regex sRx = new System.Text.RegularExpressions.Regex(sRxStr);
bIsMatch = sRx.IsMatch(sLowerStr, 0);
if (bIsMatch)
{
bReturnValue = true;
}
}
return bReturnValue;
}
/// 过滤危险字符(防止Sql注入)
/// </summary>
/// <param name="contents">预检测的内容</param>
/// <returns>返回True或false</returns>
private bool HasDangerousContents(string contents)
{
bool bReturnValue = false;
if (contents.Length > 0)
{
//convert to lower
string sLowerStr = contents.ToLower();
//RegularExpressions
string sRxStr = @"(\sand\s)|(\sand\s)|(\slike\s)|(select\s)|(insert\s)|(delete\s)|(update\s[\s\S].*\sset)|(create\s)|(\stable)|(<[iframe|/iframe|script|/script])|(')|(\sexec)|(\sdeclare)|(\struncate)|(\smaster)|(\sbackup)|(\smid)|(\scount)";
//Match
bool bIsMatch = false;
System.Text.RegularExpressions.Regex sRx = new System.Text.RegularExpressions.Regex(sRxStr);
bIsMatch = sRx.IsMatch(sLowerStr, 0);
if (bIsMatch)
{
bReturnValue = true;
}
}
return bReturnValue;
}
3。 防止死锁,让处理器处理其他,可以不用线程防止UI死锁,但是影响运行速度
public void VBSleep(int time)
{
for (int i = 0; i < time; i++)
{
Application.DoEvents();
}
}
{
for (int i = 0; i < time; i++)
{
Application.DoEvents();
}
}
4。Request请求
/// <summary>
/// 进行Request连接发送
/// </summary>
/// <param name="postData"></param>
/// <returns></returns>
private string doRequest(string url,string postData)
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
request.Referer = "http://www.tfsshop.com/?";
request.ContentLength = byteArray.Length;
request.Method = "POST";
request.Timeout = 12000;
request.CookieContainer = CookieContainer;
//是否需要代理
// if (false)
// {
// // WebProxy wp = new WebProxy(Tools.Config.ProxyAdress, Tools.Config.ProxyPoint);
// //代理是否需要身份验证
//// if (Tools.Config.UseProxyPassport) wp.Credentials = new System.Net.NetworkCredential(Tools.Config.ProxyPassportName,
// // Tools.Config.ProxyPassportPassword,
// // Tools.Config.ProxyPassportDomain);
// request.Proxy = wp;
// }
string res = "";
try
{
Stream newStream = request.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = sr.ReadToEnd();
response.Close();
}
catch (Exception e)
{
res = e.Message;
}
return res;
}
/// 进行Request连接发送
/// </summary>
/// <param name="postData"></param>
/// <returns></returns>
private string doRequest(string url,string postData)
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
request.Referer = "http://www.tfsshop.com/?";
request.ContentLength = byteArray.Length;
request.Method = "POST";
request.Timeout = 12000;
request.CookieContainer = CookieContainer;
//是否需要代理
// if (false)
// {
// // WebProxy wp = new WebProxy(Tools.Config.ProxyAdress, Tools.Config.ProxyPoint);
// //代理是否需要身份验证
//// if (Tools.Config.UseProxyPassport) wp.Credentials = new System.Net.NetworkCredential(Tools.Config.ProxyPassportName,
// // Tools.Config.ProxyPassportPassword,
// // Tools.Config.ProxyPassportDomain);
// request.Proxy = wp;
// }
string res = "";
try
{
Stream newStream = request.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = sr.ReadToEnd();
response.Close();
}
catch (Exception e)
{
res = e.Message;
}
return res;
}
5。PictureBox异步加载图片
void loadGoodImage(string id)
{
//图片异步加载完成后的处理事件
pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
//图片加载时,显示等待光标
pictureBox1.UseWaitCursor = true;
//采用异步加载方式
pictureBox1.WaitOnLoad = false;
//开始异步加载,图片的地址,请自行更换
//连接服务器获得图片
pictureBox1.LoadAsync(string.Format("http://imgs.tfsshop.com/shop/l/{0}.jpg", id));
}
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
//图片加载完成后,将光标恢复
pictureBox1.UseWaitCursor = false;
}
{
//图片异步加载完成后的处理事件
pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
//图片加载时,显示等待光标
pictureBox1.UseWaitCursor = true;
//采用异步加载方式
pictureBox1.WaitOnLoad = false;
//开始异步加载,图片的地址,请自行更换
//连接服务器获得图片
pictureBox1.LoadAsync(string.Format("http://imgs.tfsshop.com/shop/l/{0}.jpg", id));
}
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
//图片加载完成后,将光标恢复
pictureBox1.UseWaitCursor = false;
}
6。 ini配置文件操作类
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace TFSSHOP_CS
{
class 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 static string IniPath = Directory.GetCurrentDirectory() + "\\";
public static void writeSetting(string type, string Key, string Value)
{
WritePrivateProfileString(type, Key, Value, IniPath + "Setting.ini");
}
public static string readSetting(string type, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(type, Key, "", temp, 255, IniPath + "Setting.ini");
return temp.ToString();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace TFSSHOP_CS
{
class 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 static string IniPath = Directory.GetCurrentDirectory() + "\\";
public static void writeSetting(string type, string Key, string Value)
{
WritePrivateProfileString(type, Key, Value, IniPath + "Setting.ini");
}
public static string readSetting(string type, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(type, Key, "", temp, 255, IniPath + "Setting.ini");
return temp.ToString();
}
}
}
7。 移除 ALT + TAB LIST 图标
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr window, int index, int
value);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr window, int index);
const int GWL_EXSTYLE = -20;
const int WS_EX_TOOLWINDOW = 0x00000080;
const int WS_EX_APPWINDOW = 0x00040000;
public static extern int SetWindowLong(IntPtr window, int index, int
value);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr window, int index);
const int GWL_EXSTYLE = -20;
const int WS_EX_TOOLWINDOW = 0x00000080;
const int WS_EX_APPWINDOW = 0x00040000;
8。 获得任务栏高度
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string strClassName, int nptWindowName);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll", EntryPoint = "GetWindowRect")]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
private int getWindowTackHeight()
{
IntPtr hWnd = FindWindow("Shell_TrayWnd", 0);
RECT rc = new RECT();
int i_Height = 0;
try
{
GetWindowRect(hWnd, ref rc);
i_Height = rc.Bottom - rc.Top;
}
catch
{
}
return i_Height;
}
public static extern IntPtr FindWindow(string strClassName, int nptWindowName);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll", EntryPoint = "GetWindowRect")]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
private int getWindowTackHeight()
{
IntPtr hWnd = FindWindow("Shell_TrayWnd", 0);
RECT rc = new RECT();
int i_Height = 0;
try
{
GetWindowRect(hWnd, ref rc);
i_Height = rc.Bottom - rc.Top;
}
catch
{
}
return i_Height;
}
7。 窗体随鼠标移动
//鼠标拖动相关变量
private Point oldPoint = new Point(0, 0);
//记录鼠标按下变量
private bool mouseDown = false;
#region 构造函数
public myForm() {
//设置窗体相应窗体随鼠标移动事件
this.FormOnMove = true;
}
#endregion
#region 属性
//属性相关变量定义
private bool formOnMove = false;
private bool controlsOnMove = false;
/// <summary>
/// 窗体随鼠标移动
/// </summary>
public bool FormOnMove {
get {
return formOnMove;
}
set {
if (value) {
this.MouseDown += new MouseEventHandler(frm_MouseDown);
this.MouseUp += new MouseEventHandler(frm_MouseUp);
this.MouseMove += new MouseEventHandler(frm_MouseMove);
}
else {
this.MouseDown -= new MouseEventHandler(frm_MouseDown);
this.MouseUp -= new MouseEventHandler(frm_MouseUp);
this.MouseMove -= new MouseEventHandler(frm_MouseMove);
}
formOnMove = value;
}
}
/// <summary>
/// 窗体上的控件随鼠标移动
/// </summary>
public bool ControlsOnMove{
get{
return controlsOnMove;
}
set{
if (value) {
foreach (Control ctr in this.Controls) {
ctr.MouseDown += new MouseEventHandler(frm_MouseDown);
ctr.MouseUp += new MouseEventHandler(frm_MouseUp);
ctr.MouseMove += new MouseEventHandler(frm_MouseMove);
}
}
else {
foreach (Control ctr in this.Controls) {
ctr.MouseDown -= new MouseEventHandler(frm_MouseDown);
ctr.MouseUp -= new MouseEventHandler(frm_MouseUp);
ctr.MouseMove -= new MouseEventHandler(frm_MouseMove);
}
}
controlsOnMove = value;
}
}
#endregion
#region 窗体随鼠标移动相关方法
/// <summary>
/// 鼠标移动时窗体移动方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frm_MouseMove(object sender, MouseEventArgs e) {
if (mouseDown) {
this.Left += (e.X - oldPoint.X);
this.Top += (e.Y - oldPoint.Y);
}
}
/// <summary>
/// 鼠标抬起方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frm_MouseUp(object sender, MouseEventArgs e) {
mouseDown = false;
FormList.Instance.frmMove(this);
}
/// <summary>
/// 鼠标按下方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frm_MouseDown(object sender, MouseEventArgs e) {
oldPoint = e.Location;
mouseDown = true;
}
#endregion
#region 方法
8。 将Webbrowser 中的Cookie存储到CookieContainer
public void setCookie()
{
//String 的Cookie 要转成 Cookie型的 并放入CookieContainer中
Main.CookieContainer = new System.Net.CookieContainer();
if (webBrowser1.Document != null)
{
Main.cookstr = webBrowser1.Document.Cookie.Split(';');
foreach (string str in Main.cookstr)
{
string[] cookieNameValue = str.Split('=');
string name = cookieNameValue[0].Trim();
string value = "";
for (int i = 1; i < cookieNameValue.Length; i++)
{
value += cookieNameValue[i];
if (i < cookieNameValue.Length - 1) value += "=";
value = value.Trim();
}
Cookie ck = new Cookie(name, value);
ck.Domain = "www.tfsshop.com";//必须写对
Main.CookieContainer.Add(ck);
}
}
}
{
//String 的Cookie 要转成 Cookie型的 并放入CookieContainer中
Main.CookieContainer = new System.Net.CookieContainer();
if (webBrowser1.Document != null)
{
Main.cookstr = webBrowser1.Document.Cookie.Split(';');
foreach (string str in Main.cookstr)
{
string[] cookieNameValue = str.Split('=');
string name = cookieNameValue[0].Trim();
string value = "";
for (int i = 1; i < cookieNameValue.Length; i++)
{
value += cookieNameValue[i];
if (i < cookieNameValue.Length - 1) value += "=";
value = value.Trim();
}
Cookie ck = new Cookie(name, value);
ck.Domain = "www.tfsshop.com";//必须写对
Main.CookieContainer.Add(ck);
}
}
}
先记这么多,后面想起来了再整理
![](http://www.cnblogs.com/Emoticons/baimantou/21522581.gif)