在visual里面创建了一个windows服务项目,其中打开word的service已经建好了,在visual里面运行正常,打包安装到windows服务后,postman请求成功,word文件的副本也产生了,但是就是桌面没打开word,查了资料说是windows服务不能跟桌面交互,我在windows的服务里面,点击属性,勾选了可以跟桌面交互,重启服务,还是桌面没显示word窗口,救命呀,咋弄啊。
用postman发送请求,http://localhost:8080/open?filePath=C:\Users\31343\Desktop\20240924\1111.docx,这个word的文件夹产生了这个word的副本,就是桌面的word文件打不开。
代码如下,就是一个很简单的打开word的demo,
using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace second
{
public partial class WordOpenerService : ServiceBase
{
private Application wordApp;
private HttpListener listener;
private const string Url = "http://localhost:8080/";
public WordOpenerService()
{
InitializeComponent();
wordApp = new Application();
listener = new HttpListener();
listener.Prefixes.Add(Url);
}
protected override void OnStart(string[] args)
{
listener.Start();
listener.BeginGetContext(OnRequest, null);
}
protected override void OnStop()
{
listener.Stop();
wordApp.Quit();
Marshal.ReleaseComObject(wordApp);
}
private void OnRequest(IAsyncResult result)
{
var context = listener.EndGetContext(result);
listener.BeginGetContext(OnRequest, null);
string responseString = "";
try
{
var request = context.Request;
var path = request.Url.AbsolutePath.Trim('/');
if (path == "open")
{
string filePath = request.QueryString["filePath"];
OpenWord(filePath);
responseString = "Word document opened.";
}
else if (path == "edit")
{
string filePath = request.QueryString["filePath"];
string newText = request.QueryString["newText"];
EditWord(filePath, newText);
responseString = "Word document edited.";
}
else
{
responseString = "Invalid request.";
}
}
catch (Exception ex)
{
responseString = $"Error: {ex.Message}";
}
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.OutputStream.Close();
}
public void OpenWord(string filePath)
{
Document doc = wordApp.Documents.Open(filePath);
wordApp.Visible = true; // 显示 Word 窗口
}
public void EditWord(string filePath, string newText)
{
Document doc = wordApp.Documents.Open(filePath);
doc.Content.Text = newText; // 简单的替换文本
doc.Save();
doc.Close();
}
}
}