C# 64位程序调用32位微信截图工具PrScrn.dll方法


如果使用的是x86的运行方式,直接调用PrScrn.dll接口即可,siukwan/screenshot: 通过调用微信的截图dll库文件,实现微信截图功能 (github.com)

如果主程序是AnyCPU或者x64的运行方式,据我所知有下面几种方案:

1、封装成COM组件的方式太麻烦,抛弃(这个门槛有点高,而且引用繁琐,还要注册dll)

2、做成服务,采用调用服务的方式进行(感觉也很麻烦)

3、截图工具原C#调用项目地址:,采用WinAPI,SendMessage的方式进行,但是由于窗体在任务栏隐藏后会接收不到消息,因为抛弃此方案。

本人最终解决方案:

基于上面提到的项目(https://github.com/siukwan/screenshot),设置为x86的方式运行,去除多余的代码,如注册快捷键等,运行后程序自动调用截图工具,完了自己关闭,废话少说,上代码:

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);

    try
    {
        int i = DLL.PrScrn();
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScreenCaptrue.txt");
        File.WriteAllText(path, i.ToString());
    }
    catch { }
    finally
    {
        Application.Exit();
    }
}

窗体属性设置如下:

private void InitializeComponent()
{
    this.SuspendLayout();
    // 
    // Form1
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(0, 0);
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    this.Name = "Form1";
    this.ShowIcon = false;
    this.ShowInTaskbar = false;
    this.Text = "截图工具";
    this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
    this.ResumeLayout(false);
}

编译生成即可,自己放好路径。

64位程序调用方法如下:

try
{
    Process proc = new Process();
    proc.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ScreenCaptrue\ScreenCaptrue.exe");
    proc.Start();
    proc.WaitForExit();
    string resultFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ScreenCaptrue\ScreenCaptrue.txt");
    if (File.Exists(resultFilePath))
    {
        string printResult = File.ReadAllText(resultFilePath);
        if (printResult == "1")
        {
            pictureBox1.Image?.Dispose();
            Image image = Clipboard.GetImage();
            pictureBox1.Image = image;
        }
        lblResult.Text = printResult == "0" ? "取消截图" : (printResult == "1" ? "截图确认完成" : "截图工具直接保存");
    }
    else
    {
        lblResult.Text = "读取操作结果失败";
        Image image = Clipboard.GetImage();
        if (image != null)
        {
            pictureBox1.Image?.Dispose();
            pictureBox1.Image = image;
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}