我正尝试构建桌面应用程序以使用Facebook API并从朋友处获取数据。 反正我被困在登录阶段。 我使用了一些建议,并使用WebBrowser登录Facebook。它效果很好。 我被困在试图让它给我状态=失败或成功facebook桌面应用程序C#
我试图在button_1方法
if (!w.DocumentText.Contains(@"<div class=""linkWrap noCount"">Messages</div>"))
{
w.Navigate(@"http://www.facebook.com/login.php");
MessageBox.Show("Login error. Wrong username or password!");
}
else
{
MessageBox.Show("Logged in successfully");
}
的< DIV类的结尾做这样=“” linkWrap NOCOUNT” “>消息</div>仅在登录时显示,因此我使用它来查看用户是否已登录
但问题是它总是给我一个错误(错误的用户和传递),因为它读取它在浏览器完成导航到页面之前。我尝试线程和线程睡眠,甚至定时器,但它似乎并不工作
一个想法?
这里是代码:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
string email = textBox1.Text;
string password = textBox2.Text;
// create a new browser
WebBrowser w = new WebBrowser();
w.Dock = DockStyle.Fill;
this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on
// latter you may not chose to add the browser or you can even set it to invisible...
// navigate to facebook
w.Navigate(@"http://www.facebook.com/login.php");
// wait a little
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
HtmlElement temp=null;
// while we find an element by id named email
while (temp == null)
{
temp = w.Document.GetElementById("email");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once we find it place the value
temp.SetAttribute("value", email);
temp = null;
// wiat till element with id pass exists
while (temp == null)
{
temp = w.Document.GetElementById("pass");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once it exist set its value equal to passowrd
temp.SetAttribute("value", password);
// if you already found the last fields the button should also be there...
var inputs = w.Document.GetElementsByTagName("input");
int counter = 0;
bool enableClick = false;
// iterate through all the inputs in the document
foreach (HtmlElement btn in inputs)
{
try
{
var att = btn.GetAttribute("tabindex");
var name = btn.GetAttribute("id");
if (enableClick)// button to submit always has a differnt id. it should be after password textbox
{
btn.InvokeMember("click");
counter++;
}
if (name.ToUpper().Contains("PASS") || att=="4")
{
enableClick = true; // button should be next to the password input
}
// try a max of 5 times
if (counter > 5)
{
break;
}
}
catch
{
}
}
}
虽然这可能会在理论上回答这个问题,[这将是更可取的](http://meta.stackexchange.com/q/8259)在这里包括答案的基本部分,并提供供参考的链接。 – Lix 2012-02-11 12:42:24
此SDK不会以普通用户的身份登录我,但前提是我拥有应用ID,但这不是我需要的。谢谢 – Zbone 2012-02-11 14:44:56
您可以创建一个Facebook应用并将其用于连接。这是一个简单的过程,我不确定您是否可以在没有任何应用程序的情况下进行Facebook登录。当您使用SDK登录Facebook时,它必须作为应用程序请求权限。 – 2012-02-11 14:48:35