窗体应用程序防腾讯QQ源码

窗体应用程序防腾讯QQ源码

窗体应用程序防腾讯QQ源码

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aptech.UI;
using System.Data.SqlClient;
using System.Media; namespace MyQQ
{
public partial class MainForm : Form
{
int fromUserId;  // 消息的发起者
int friendFaceId; // 发消息的好友的头像Id
int messageImageIndex = ; // 工具栏中的消息图标的索引
public static int faceId = ; // 头像索引
public MainForm()
{
InitializeComponent();
} private void MainForm_Load(object sender, EventArgs e)
{
//初始化皮肤
skinEngine1.SkinFile = "SportsGreen.ssk";
// 显示个人的信息
timSound.Start();
wenti();
sbFriends.AddGroup("我的好友");
sbFriends.AddGroup("陌生人");
//this.sideBar1.AddGroup("我的好友");
//this.sideBar1.AddGroup("陌生人"); //this.sideBar1.Groups[0].Items.Add("小红1", 1);
//this.sideBar1.Groups[0].Items.Add("小红2", 1);
//this.sideBar1.Groups[0].Items.Add("小红3", 1); //SubItem sit = new SbItem("小花", 80);
//sit.Tag = 1000;
//this.sideBar1.Groups[0].Items.Add(sit);
//查看好友
ADDName(); this.Left = Screen.PrimaryScreen.WorkingArea.Width-this.Width;
//this.Top = Screen.PrimaryScreen.WorkingArea.Height - this.Width;
//this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Height; } private void ADDName()
{
//清空信息
sbFriends.Groups[].Items.Clear();
//创建sql语句(实现查询)
string sql = string.Format(
"SELECT FriendId,NickName,FaceId FROM Users,Friends WHERE Friends.HostId={0} AND Users.Id=Friends.FriendId",
UserHelper.loginId);
//执行try块语句
try
{
//创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
if (DBHelper.connection.State!= ConnectionState.Open)
{
DBHelper.connection.Open();//打开数据库连接
}
//使用变量reader来存取执行命令后的值
SqlDataReader reader = command.ExecuteReader();
//循环使用Read()方法
while (reader.Read())
{
//创建item对象(使用到ListView控件)
SbItem item = new SbItem((string)reader["NickName"], (int)reader["FaceId"]);
item.Tag = reader["FriendId"];//使用Tag临时变量来存取FrienId该列的值
sbFriends.Groups[].Items.Add(item);//执行显示(从下标0开始) }
reader.Close();//关闭reader()
}
catch (Exception ex)
{
//提示错误信息
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
}
}
private string wenti()
{
string nickName = ""; // 昵称 bool error = false; // 标识是否出现错误 // 取得当前用户的昵称、头像(实现查询)
string sql = string.Format(
"SELECT NickName, FaceId FROM Users WHERE Id={0}",
UserHelper.loginId);
//执行try块语句
try
{
// 创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//打开数据库连接
DBHelper.connection.Open();
//执行command命令
SqlDataReader dataReader = command.ExecuteReader();
//循环使用Read()方法
if (dataReader.Read())
{
if (!(dataReader["NickName"] is DBNull)) // 判断数据库类型是否为空
{
nickName = Convert.ToString(dataReader["NickName"]);
}
//使用变量faceId来存取数据类型转换后的值
faceId = Convert.ToInt32(dataReader["FaceId"]);
}
//关闭dataReader()
dataReader.Close();
}
catch (Exception ex)
{
//提示错误信息
error = true;
Console.WriteLine(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
} // 根据操作数据库结果进行不同的操作
if (error)
{
//提示用户信息
MessageBox.Show("服务器请求失败!请重新登录!", "意外错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();//退出当前应用程序
}
else
{
// 在窗体标题显示登录的昵称、号码
this.Text = UserHelper.loginId.ToString();
this.picboName.Image = imglstBig.Images[faceId];
this.label1.Text = string.Format("{0}({1})", nickName, UserHelper.loginId.ToString()); }
return sql;
} private void tsmiView_Click(object sender, EventArgs e)
{
if (sbFriends.View == SbView.LargeIcon)
{
sbFriends.View = SbView.SmallIcon;
tsmiView.Text = "显示大图像";
}
else if (sbFriends.View == SbView.SmallIcon)
{
sbFriends.View = SbView.LargeIcon;
tsmiView.Text = "显示小图像";
}
} private void sbFriends_ItemDoubleClick(SbItemEventArgs e)
{
ChatForm chat = new ChatForm();
chat.friendId = Convert.ToInt32(e.Item.Tag); // 号码
chat.nickName = e.Item.Text; // 昵称
chat.faceId = e.Item.ImageIndex; // 头像
timer2.Stop();//点击收取信息后图片停止换取
timer1.Stop();
chat.Show();
} private void picboName_Click(object sender, EventArgs e)
{
PersonalInfoForm face = new PersonalInfoForm();
face.Show();
} private void timer1_Tick(object sender, EventArgs e)
{ } private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
} private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
skinEngine1.SkinFile = "SportsGreen.ssk";
label1.ForeColor =Color.BlueViolet;
sbFriends.ForeColor = Color.BlanchedAlmond;
sbFriends.GroupHeaderBackColor = Color.Green;
sbFriends.BackColor = Color.SpringGreen;
} private void 黑色ToolStripMenuItem_Click(object sender, EventArgs e)
{
skinEngine1.SkinFile = "SteelBlack.ssk";
label1.ForeColor = Color.White;
sbFriends.ForeColor = Color.Black;
sbFriends.GroupHeaderBackColor = Color.Black;
sbFriends.BackColor = Color.Gray;
} private void 橙色ToolStripMenuItem_Click(object sender, EventArgs e)
{
skinEngine1.SkinFile = "SportsOrange.ssk";
label1.ForeColor = Color.Black;
sbFriends.ForeColor = Color.White;
sbFriends.GroupHeaderBackColor = Color.Orange;
sbFriends.BackColor = Color.HotPink;
} private void toolStripButton2_Click(object sender, EventArgs e)
{ SearchFriendForm Search = new SearchFriendForm();
Search.Show();
} private void tsbSound_Click(object sender, EventArgs e)
{ timer1.Stop(); // 消息timer停止运行
// 图片恢复正常
messageImageIndex = ;
tsbSound.Image = imageList1.Images[messageImageIndex]; string sql = string.Format("select FromUserId from dbo.Messages where MessageState = 0 and MessageTypeId = 2 and ToUserId ={0}", UserHelper.loginId); SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
int FromUserId = Convert.ToInt32(command.ExecuteScalar()); DBHelper.connection.Close();
RequestForm request = new RequestForm();
request.Show(); }
//系统信息,喇叭闪动
private void timer1_Tick_1(object sender, EventArgs e)
{
messageImageIndex = messageImageIndex == ? : ;//如果messageImageIndex为0就将1赋给它,否则就将0赋给他
tsbSound.Image = imageList1.Images[messageImageIndex]; SoundPlayer soundPlay = new SoundPlayer("system.wav");
soundPlay.Play(); }
/// <summary>
/// 读取数据库消息启动计时器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timSound_Tick(object sender, EventArgs e)
{ }
/// <summary>
/// 更新陌生人列表
/// </summary>
private void UpdateStranger(int loginId)
{
// 选出这个人的基本信息
string sql = "SELECT NickName, FaceId FROM Users WHERE Id=" + loginId;
bool error = false; // 用来标识是否出现错误
try
{
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
SqlDataReader dataReader = command.ExecuteReader(); // 查询
if (dataReader.Read())
{
SbItem item = new SbItem((string)dataReader["NickName"], (int)dataReader["FaceId"]);
item.Tag = this.fromUserId; // 将Id记录在Tag属性中
sbFriends.Groups[].Items.Add(item); // 向陌生人组中添加项
}
sbFriends.VisibleGroup = sbFriends.Groups[]; // 设定陌生人组为可见组
}
catch (Exception ex)
{
error = true;
Console.WriteLine(ex.Message);
}
finally
{
DBHelper.connection.Close();
} // 出错了
if (error)
{
MessageBox.Show("服务器出现意外错误!", "抱歉", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 判断发消息的人是否在列表中
/// </summary>
private bool HasShowUser(int loginId)
{
bool find = false; // 表示是否在当前显示出的用户列表中找到了该用户 // 循环 SideBar 中的2个组,寻找发消息的人是否在列表中
for (int i = ; i < ; i++)
{
for (int j = ; j < sbFriends.Groups[i].Items.Count; j++)
{
if (Convert.ToInt32(sbFriends.Groups[i].Items[j].Tag) == loginId)
{
find = true;
}
}
}
return find;
} private void timer2_Tick(object sender, EventArgs e)
{
// 循环好友列表两个组中的每个item,找到发消息的好友,让他的头像闪烁
for (int i = ; i < ; i++)
{
for (int j = ; j < sbFriends.Groups[i].Items.Count; j++)
{
if (Convert.ToInt32(sbFriends.Groups[i].Items[j].Tag) == this.fromUserId)
{
if (sbFriends.Groups[i].Items[j].ImageIndex < )
{
sbFriends.Groups[i].Items[j].ImageIndex = ;// 索引为100的图片是一个空白图片
}
else
{
sbFriends.Groups[i].Items[j].ImageIndex = this.friendFaceId;
}
sbFriends.Invalidate(); // 重新绘制,只要告诉学生需要这句话才能正常闪烁头像就行 }
}
}
SoundPlayer sound = new SoundPlayer("msg.wav");
sound.Play(); } private void sbFriends_Load(object sender, EventArgs e)
{ } private void timSound_Tick_1(object sender, EventArgs e)
{
ADDName(); // 刷新好友列表
int messageTypeId = ; // 消息类型
int messageState = ; // 消息状态 // 找出未读消息对应的好友Id
string sql = string.Format(
"SELECT Top 1 FromUserId, MessageTypeId, MessageState FROM Messages WHERE ToUserId={0} AND MessageState=0", UserHelper.loginId);
SqlCommand command;
try
{
command = new SqlCommand(sql, DBHelper.connection);
if (DBHelper.connection.State != ConnectionState.Open)
{
DBHelper.connection.Open();
}
SqlDataReader dataReader = command.ExecuteReader(); // 循环读出一个未读消息
if (dataReader.Read())
{
this.fromUserId = (int)dataReader["FromUserId"];
messageTypeId = (int)dataReader["MessageTypeId"];
messageState = (int)dataReader["MessageState"];
}
dataReader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
DBHelper.connection.Close();
} // 判断消息类型,如果是添加好友消息,就启动喇叭timer,让小喇叭闪烁
if (messageTypeId == && messageState == )
{
// SoundPlayer player = new SoundPlayer("system.wav");
//player.Play();
timer1.Start();//启动闪喇叭的计时器
}
// 如果是聊天消息,就启动聊天timer,让好友头像闪烁
else if (messageTypeId == && messageState == )
{
// 获得发消息的人的头像Id
sql = "SELECT FaceId FROM Users WHERE Id=" + this.fromUserId;
try
{
command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
this.friendFaceId = Convert.ToInt32(command.ExecuteScalar()); // 查找到发消息的好友的头像索引
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
DBHelper.connection.Close();
} // 如果发消息的人没有在好友列表中就添加到陌生人列表中
if (!HasShowUser(fromUserId))
{
UpdateStranger(fromUserId);
}
// SoundPlayer player = new SoundPlayer("msg.wav");
//player.Play();
timer2.Start(); // 启动闪烁头像定时器
}
} private void toolStripButton1_Click(object sender, EventArgs e)
{
PersonalInfoForm person = new PersonalInfoForm();
person.Show();
} private void toolStripButton5_Click(object sender, EventArgs e)
{
Application.Exit();
} private void update_Tick(object sender, EventArgs e)
{
//查看好友
ADDName();
wenti();
} private void tsmiDelete_Click(object sender, EventArgs e)
{
string FriendId = sbFriends.SeletedItem.Tag.ToString();
sbFriends.SeletedItem.Parent.Items.Remove(sbFriends.SeletedItem); string sql = string.Format("delete from dbo.Friends where HostId={0} and FriendId={1}", UserHelper.loginId, FriendId);
SqlCommand com = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
int reader = com.ExecuteNonQuery();
if (reader == )
{
MessageBox.Show("成功");
}
else
{
MessageBox.Show("失败");
} DBHelper.connection.Close();
} private void tsb_Click(object sender, EventArgs e)
{
ADDName();
wenti();
} private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult res = MessageBox.Show("你确定关吗?", "温馨提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (res == DialogResult.OK)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
} private void timer3_Tick(object sender, EventArgs e)
{
headForm();
} private void headForm()
{
string nickName = "";
// 取得当前用户的昵称、头像
string sql = string.Format(
"SELECT NickName, FaceId FROM Users WHERE Id={0}",
UserHelper.loginId);
try
{
// 查询
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
SqlDataReader dataReader = command.ExecuteReader(); if (dataReader.Read())
{ nickName = Convert.ToString(dataReader["NickName"]); faceId = Convert.ToInt32(dataReader["FaceId"]);
}
dataReader.Close();
}
catch (Exception ex)
{ Console.WriteLine(ex.Message);
}
finally
{
DBHelper.connection.Close();
} // 在窗体标题显示登录的昵称、号码 this.picboName.Image = imglstBig.Images[faceId];
} private void 沉默是金ToolStripMenuItem_Click(object sender, EventArgs e)
{
skinEngine1.SkinFile = "MSN.ssk";
} private void MainForm_MouseHover(object sender, EventArgs e)
{ } private void MainForm_MouseMove(object sender, MouseEventArgs e)
{
//this.Left = Screen.PrimaryScreen.WorkingArea.Width-20; }
private void MainForm_MouseEnter(object sender, EventArgs e)
{
// if (this.Left == Screen.PrimaryScreen.WorkingArea.Width - 10)
// {
//this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width - 100;
// }
// else
// {
// this.Top = Screen.PrimaryScreen.WorkingArea.Height - 10;
//} } private void MainForm_MouseLeave(object sender, EventArgs e)
{ } private void MainForm_MouseClick(object sender, MouseEventArgs e)
{ }
}
}
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MyQQ
{
public partial class ChatForm : Form
{
public int friendId; // 当前聊天的好友号码
public string nickName; // 当前聊天的好友昵称
public int faceId; // 当前聊天的好友头像Id
string messageIdsString = ""; // 消息的Id组成的字符串
string message; // 消息内容
string messageTime; // 消息发出的时间
public ChatForm()
{
InitializeComponent();
} private void ChatForm_Load(object sender, EventArgs e)
{ this.Text = string.Format("与{0}聊天中...", nickName); // 设置窗体标题
lblFriend.Text = string.Format("{0}({1})", nickName, friendId); //当前聊天的好友昵称和号码
picFace.Image = ilFace.Images[faceId]; // 读取所有的未读消息,显示在窗体中
Showview();
} private void Showview()
{
string str = string.Format(
"SELECT Id, Message,MessageTime From Messages WHERE FromUserId={0} AND ToUserId={1} AND MessageTypeId=1 AND MessageState=0",
friendId, UserHelper.loginId); try
{
SqlCommand com = new SqlCommand(str, DBHelper.connection);
DBHelper.connection.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
messageIdsString += Convert.ToString(reader["Id"]) + "_";
message = Convert.ToString(reader["Message"]);
messageTime = Convert.ToDateTime(reader["MessageTime"]).ToString();
txtMessage.Text += string.Format("\n{0} {1}\n {2}", nickName, messageTime, message);
}
reader.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);
}
finally
{
DBHelper.connection.Close();
} if (messageIdsString.Length > ) //查看Id是否有效
{
messageIdsString.Remove(messageIdsString.Length - );
NewMethod(messageIdsString, '_');
}
} private void NewMethod(string messageIdsString, char separator)
{
string[] chai = messageIdsString.Split(separator);
string sql = "update Messages set MessageState=1 where Id=";
string updateSql;
try
{
SqlCommand com = new SqlCommand(); com.Connection = DBHelper.connection;
DBHelper.connection.Open();
foreach (string id in chai)
{
if (id != "")
{
updateSql = sql + id;
com.CommandText = updateSql;
int result = com.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); }
finally
{
DBHelper.connection.Close();
}
} private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSend_Click(object sender, EventArgs e)
{
//判断txtWrit该控件是否为空,如是提示用户信息
if (txtWrit.Text.Trim() == "")
{
MessageBox.Show("请输入信息!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//判断数组长度是否大于等于150,如果大于等于150其实用户信息
else if (txtWrit.Text.Trim().Length >= )
{
MessageBox.Show("此消息过长!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//否则,执行try块语句(实现增加信息)
else
{
try
{
//创建sql语句实现增加信息
string sql = string.Format(
"insert into Messages(FromUserId,ToUserId,Message,MessageTypeId,MessageState) values({0},{1},'{2}',1,0)",
UserHelper.loginId, friendId, txtWrit.Text.Trim());
//创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//打开数据库连接
DBHelper.connection.Open();
//执行非查询(增加)命令
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//提示错误信息
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
}
} } }
}

ChatForm

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;//导入命名空间
namespace MyQQ
{
public partial class FaceForm : Form
{ public FaceForm()
{
InitializeComponent();
} private void butfaceNO_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("确定要退出吗?","温馨提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (result==DialogResult.OK)
{
this.Close();//执行关闭当前窗体语句块
} } private void butfaceOK_Click(object sender, EventArgs e)
{
//判断是否选中图像,如果未选中图像点击确定的时候提示用户信息是否退出
if (listface.SelectedItems.Count==)
{
DialogResult result= MessageBox.Show("确定要退出吗?","温馨提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
if (result == DialogResult.OK)
{
this.Close();//执行关闭当前窗体
}
}
else
{
//使用变量faceIds来存取选中的该图片
int faceIds = listface.SelectedItems[].ImageIndex; try
{
//创建sql语句(更新语句)
string sql = string.Format(
"update Users set FaceId={0} where Id={1}",
faceIds, UserHelper.loginId);
//创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//打开数据库连接
DBHelper.connection.Open();
//执行非查询命令(更新)
int result = command.ExecuteNonQuery();
if (result > )
{
MessageBox.Show("操作成功!");//提示用户信息操作成功
}
else
{
MessageBox.Show("操作失败!");//提示用户信息操作失败
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);//提示错误信息
}
finally
{
DBHelper.connection.Close();//关闭数据库连接
} } } private void FaceForm_Load(object sender, EventArgs e)
{
//执行在加载的时候显示信息(ListView控件)
for (int i = ; i < ilFaces.Images.Count; i++)
{
//执行增加项语句块(从下标为0开始进行显示)
listface.Items.Add(i.ToString());
listface.Items[i].ImageIndex = i; }
}
}
}

FaceForm

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;//导入命名空间
namespace MyQQ
{
public partial class RegisterForm : Form
{
string sex = "";//声明一个成员变量并且初始化 public RegisterForm()
{
InitializeComponent();
} private void button2_Click(object sender, EventArgs e)
{
this.Close();
} private void button1_Click(object sender, EventArgs e)
{ if (rbt.Checked)
{
sex="男";
Register();
}
else
{
sex="女";
Register();
} } private void Register()
{
if (tbopwd1.Text == tbopwd.Text)
{
int star = ;
int boo = ;
switch (BooldStyle.Text)
{
case "A型":
boo = ;
break;
case "B型":
boo = ;
break;
case "O型":
boo = ;
break;
default:
boo = ;
break;
}
switch (Star.Text)
{
case "白羊座":
star = ;
break;
case "双子座":
star = ;
break;
case "巨蟹座":
star = ;
break;
case "狮子座":
star = ;
break;
case "处女座":
star = ;
break;
case "天秤座":
star = ;
break;
case "天蝎座":
star = ;
break;
case "射手座":
star = ;
break;
case "摩羯座":
star = ;
break;
case "水瓶座":
star = ;
break;
case "双鱼座":
star = ;
break;
default:
star = ;
break;
} try
{
string sql = string.Format("insert into dbo.Users(Age,Sex,LoginPwd,NickName,Name,StarId,BloodTypeId) values({0},'{1}','{2}','{3}','{4}','{5}',{6})", tboAge.Text, sex, tbopwd.Text, tboName.Text, ming.Text, star, boo);
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
int result = command.ExecuteNonQuery();
if (result == )
{
//查询新增加的记录的标识号的代码
sql = "select @@Identity from Users";
command.CommandText = sql; //新增指定command对象的SQL语句 //执行查询语句
int num = Convert.ToInt32(command.ExecuteScalar());
string a = string.Format("注册成功!你的MyQQ号是{0}", num);
MessageBox.Show(a, "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
} }
catch (Exception ex)
{ MessageBox.Show(ex.Message);
}
finally
{
DBHelper.connection.Close();
}
}
else
{
MessageBox.Show("你的两次密码输入不相同!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); }
} }
}

RegisterForm

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MyQQ
{
public partial class SearchFriendForm : Form
{
bool a = false;//声明一个布尔型的变量a并初始值设为false
private DataSet dataset = new DataSet();//创建datasSet对象
private SqlDataAdapter adapter;//声明变量adaper public SearchFriendForm()
{
InitializeComponent();
} /// <summary>
/// 点击查找的事件
/// </summary>
private void btnSerch_Click_1(object sender, EventArgs e)
{
panel1.Visible = true;//将panel1设为true(显示)
//创建sql语句(实现查询)
string sql = "select Id,NickName,Age,Sex from Users";
//给变量赋值
adapter = new SqlDataAdapter(sql, DBHelper.connection);
//使用SqlDataAdaper对象的Fill()方法进行填充
adapter.Fill(dataset);
//执行显示(下标从0开始)
dtVsearch.DataSource = dataset.Tables[]; if (tabSearch.SelectedIndex == )
{ //精确查找
rigorSearch();
}
else
{
//高级查找
AdvancedSearch(); }
}
/// <summary>
/// 点击加为好友的事件
/// </summary>
private void btnAdd_Click(object sender, EventArgs e)
{
//要加朋友的QQ号码
int friendId = searchID();
//判断是否已被加
a = HasAdded(friendId); //好友策略
//count等于1:允许任何人加我为好友
//count等于2:需要身份验证才能加我为好友
//count等于3:不允许任何人加我为好友
int count = tactic(friendId);
if (friendId==UserHelper.loginId)
{
MessageBox.Show("不可以加自己为好友");
}
//可以直接加
else if (a == false && count == )
{
MessageBox.Show("添加成功");
//添加操作
addFriendId(friendId); }
else if (a == false && count == )
{
MessageBox.Show("对方需要验证,验证消息已发出");
if (friendId!=UserHelper.loginId)
{
tacticres(friendId);
}
//验证添加
}
else if (a == true)
{
MessageBox.Show("已是你的好友了");
}
else
{
MessageBox.Show("添加失败,对方不应许任何人加为好友");
}
}
/// <summary>
/// 点击上一步的事件
/// </summary>
private void btnBack_Click(object sender, EventArgs e)
{
this.panel1.Visible = false;//将panel1初始设为false (不可见)
}
/// <summary>
/// 点击关闭的事件
/// </summary>
private void butoff_Click(object sender, EventArgs e)
{
this.Close();//关闭当前窗体
}
/// <summary>
/// 点击关闭的事件
/// </summary>
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();//关闭当前窗体
} //高级查找方法
private void AdvancedSearch()
{
//创建sql语句(查询语句)
string sql = "";
sql = "SELECT Id,NickName,Age,Sex FROM Users";
//声明变量初始化和使用变量来存取对应的值
string termComAge = "";
string termComSex = comSex.Text;
//使用switch结构来实现年龄在某个范围内进行运用
switch (comAge.SelectedIndex)
{
case :
termComAge = " Age>=0 AND Age<10";
break;
case :
termComAge = " Age>=10 AND Age<20";
break;
case :
termComAge = " Age>=20 AND Age<30";
break;
case :
termComAge = " Age>=30 AND Age<40";
break;
case :
termComAge = " Age>=40 AND Age<50";
break;
case :
termComAge = " Age>=50";
break;
default:
termComAge = "";
break;
}
//判断如果这两个控件的值如果都为空的话,提示用户相应的信息
if (termComAge == "" && termComSex == "")
{
MessageBox.Show("你还没有选择的啊??");
return;
}
//判断如果这两个控件的值如果不为空的话,进行相应的计算
else
{
if (termComAge != "" && termComSex == "")
{
sql += string.Format(" where {0}", termComAge);
}
else if (termComAge == "" && termComSex != "")
{
sql += string.Format(" where Sex='{0}'", termComSex);
}
else
{
sql += string.Format(" where {0} AND Sex='{1}'", termComAge, termComSex);
} }
//清空表中的信息
dataset.Tables[].Clear();
//给变量赋值
adapter = new SqlDataAdapter(sql, DBHelper.connection);
//使用SqldataAdaper对象的fill()方法进行填充
adapter.Fill(dataset);
//执行显示语句块(并且下标从0开始)
dtVsearch.DataSource = dataset.Tables[];
}
//精确查找方法
private void rigorSearch()
{
//创建sql语句块(实现查询)
string sql = ""; sql = "SELECT Id,NickName,Age,Sex FROM Users"; if (radexactitude.Checked == true)
{
if (friendQQ.Text == "" && friendName.Text == "")
{ //MessageBox.Show("你还没有填条件的啊@ !@");
}
else if (friendQQ.Text != "" && friendName.Text == "")
{
sql += string.Format(" where ID={0}", int.Parse(friendQQ.Text.Trim()));
}
else
{
sql += string.Format(" where NickName like '%{0}%'", friendName.Text);
}
}
//清空表中的信息
dataset.Tables[].Clear();
//给变量赋值
adapter = new SqlDataAdapter(sql, DBHelper.connection);
//使用SqldataAdaper对象的fill()方法进行填充
adapter.Fill(dataset);
//执行显示语句块(并且下标从0开始)
dtVsearch.DataSource = dataset.Tables[];
}
//发送验证请求方法
private int tacticres(int friendId)
{
int result = ; // 操作结果
string sql = string.Format("INSERT INTO Messages (FromUserId, ToUserId, MessageTypeId, MessageState) VALUES ({0},{1},{2},{3})",
UserHelper.loginId, friendId, , );
try
{
// 执行添加操作
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//打开数据库连接
DBHelper.connection.Open();
//使用变量result来存取执行命令后的值
result = command.ExecuteNonQuery();
if(result>)
{
MessageBox.Show("操作成功!");//提示用户信息操作成功
}
else
{
MessageBox.Show("操作失败!");//提示用户信息操作失败
}
}
catch (Exception ex)
{
//提示错误信息
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
}
return result;
}
//添加操作方法
private int addFriendId(int friendId)
{
int result = ; DBHelper.connection.Open();
try
{
string sql = string.Format("insert into dbo.Friends(HostId,FriendId)values ({0},{1})", UserHelper.loginId, friendId);
//创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//执行命令(使用变量result来存取执行后的值)
result = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//提示错误信息
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
}
return result;
}
//好友策略方法
private int tactic(int friendId)
{ int count = ;//声明变量count并且初始化
try
{
//创建sql语句块(实现查询)
string sql = string.Format("select FriendshipPolicyId from dbo.Users where id={0}", friendId);
//创建command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
//打开数据库连接
DBHelper.connection.Open();
//执行命令(并且使用变量count来存取,在之前也要进行转换为整型)
count = int.Parse(command.ExecuteScalar().ToString()); }
catch (Exception ex)
{
//提示错误信息
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close();
}
return count;
}
//获取要加的朋友的QQ号码方法
private int searchID()
{
int friendId = ; //当没有选中任何一行
if (dtVsearch.SelectedRows.Count == )
{
MessageBox.Show("请选择一个好友!");
}
//确保第一个单元格有值
else if (dtVsearch.SelectedRows[].Cells[] != null)
{
//获得第一个单元格的值
friendId = int.Parse(dtVsearch.SelectedRows[].Cells[].Value.ToString()); }
return friendId;
}
//是否已被加的方法
public bool HasAdded(int friendId)
{
//创建sql语句(实现查询)
string sql = string.Format("select id from dbo.Friends where HostId ={0} and FriendId={1}", UserHelper.loginId, friendId);
//打开数据库连接
DBHelper.connection.Open();
//执行try块语句
try
{
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
string reader = Convert.ToString(command.ExecuteScalar());
//不可以加
if (reader != "")
{
this.a = true;
}
//可以加
else
{
this.a = false;
} }
catch (Exception ex)
{
//提示错误信息
Console.WriteLine(ex.Message);
}
finally
{
//关闭数据库连接
DBHelper.connection.Close(); }
return a;
} private void SearchFriendForm_Load(object sender, EventArgs e)
{ } }
}

SearchFriendForm

04-28 20:28