You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# WPF项目中使用TweetInvi展示主页时间线及用户头像用户名

问题解答

你的整体实现思路没有问题,问题出在没有正确提取单条推文对应的发布者属性:

核心调整点

  • TweetInvi返回的时间线列表中每个元素都是ITweet类型对象,其自带的CreatedBy属性对应发布该推文的用户对象,可直接从中读取你需要的信息:
    • 用户名:CreatedBy.Name(用户自定义显示名)、CreatedBy.ScreenName(账号@名)
    • 用户头像地址:CreatedBy.ProfileImageUrl
  • 你原有代码中直接Convert.ToString(homeTimeline[i])输出的是ITweet对象的默认字符串序列化结果,不是推文内容,要获取推文正文请使用homeTimeline[i].Text

调整后的代码示例

TwitterClient userClient = new TwitterClient("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");

public Form1()
{
    InitializeComponent();
}
public async void Form1_Load(object sender, EventArgs e)
{
    var user = await userClient.Users.GetAuthenticatedUserAsync();
    label1.Text = user.Name + " @" + user.ScreenName;

    var homeTimeline = await userClient.Timelines.GetHomeTimelineAsync();

    int avatarLeft = 20; // 头像左侧坐标
    int nameLeft = 100; // 用户名左侧坐标
    int contentLeft = 100; // 推文内容左侧坐标
    int top = 281; // 起始顶部坐标

    for (int i = 0; i < homeTimeline.Length; i++)
    {
        var currentTweet = homeTimeline[i];
        var tweetAuthor = currentTweet.CreatedBy;
        
        // 添加头像控件
        PictureBox avatarBox = new PictureBox();
        avatarBox.Location = new Point(avatarLeft, top);
        avatarBox.Size = new Size(60, 60);
        avatarBox.SizeMode = PictureBoxSizeMode.StretchImage;
        // 异步加载头像避免卡UI
        avatarBox.LoadAsync(tweetAuthor.ProfileImageUrl);
        this.Controls.Add(avatarBox);
        
        // 添加用户名标签
        Label nameLabel = new Label();
        nameLabel.Location = new Point(nameLeft, top);
        nameLabel.Text = $"{tweetAuthor.Name} @{tweetAuthor.ScreenName}";
        nameLabel.Font = new Font(nameLabel.Font, FontStyle.Bold);
        nameLabel.AutoSize = true;
        this.Controls.Add(nameLabel);
        
        // 添加推文内容标签
        Label contentLabel = new Label();
        contentLabel.Location = new Point(contentLeft, top + 20);
        contentLabel.Text = currentTweet.Text;
        contentLabel.AutoSize = true;
        contentLabel.MaximumSize = new Size(400, 0); // 限制宽度自动换行
        this.Controls.Add(contentLabel);
        
        // 计算下一条推文的顶部坐标,留出间距
        top += Math.Max(60, contentLabel.Height + 20) + 15;
    }
}

额外注意事项

  • 如果需要加载更高清的头像,可以将ProfileImageUrl末尾的_normal替换为_400x400即可获取大尺寸头像
  • 建议后续改用流式布局控件(如FlowLayoutPanel)来承载每条推文的控件,避免手动计算坐标出现布局错乱

内容的提问来源于stack exchange,提问作者HamzaDamiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:36:06