我正在努力尝试关闭特定的内容MessageBox(如果它根据标题和文本显示)。MessageBox当没有图标时我可以使用它。
IntPtr handle = FindWindowByCaption(IntPtr.Zero, "Caption");
if (handle == IntPtr.Zero)
return;
//Get the Text window handle
IntPtr txtHandle = FindWindowEx(handle, IntPtr.Zero, "Static", null);
int len = GetWindowTextLength(txtHandle);
//Get the text
StringBuilder sb = new StringBuilder(len + 1);
GetWindowText(txtHandle, sb, len + 1);
//close the messagebox
if (sb.ToString() == "Original message")
{
SendMessage(new HandleRef(null, handle), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
Run Code Online (Sandbox Code Playgroud)
MessageBox当显示没有像下面这样的图标时,上面的代码工作得很好。
MessageBox.Show("Original message", "Caption");
Run Code Online (Sandbox Code Playgroud)
但是,如果它包含如下所示的图标(来自MessageBoxIcon),则它不起作用;GetWindowTextLength返回 0 并且什么也没有发生。
MessageBox.Show("Original message", "Caption", MessageBoxButtons.OK, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用IHostedService创建后台服务.如果我只有一个后台服务,一切正常.当我尝试创建多个实现时,IHostedService只有第一个实际运行的实现.
services.AddSingleton<IHostedService, HostedServiceOne>();
services.AddSingleton<IHostedService, HostedServiceTwo>();
Run Code Online (Sandbox Code Playgroud)
在上面的例子StartAsync上HostedServiceOne被调用,但StartAsync上HostedServiceTwo不会被调用.如果我换登记的两种实现方式的顺序IHostedService(把IHostedServiceTwo前IHostedServiceOne),然后StartAsync在HostedServiceTwo被调用而从来不是HostedServiceOne.
编辑:
我被引导到以下内容:
然而,这不适合IHostedService.要使用建议的方法,我将不得不打电话,serviceProvider.GetServices<IService>();但似乎IHostedService.StartAsync似乎在内部调用.我甚至不确定我会在哪里触发它IHostedService.StartAsync.
我正在处理一个 ASP.NET Core 2.1 项目,我需要在其中注册,然后在 Startup.ConfigureServices 中使用单例服务。
我有以下代码:
public void ConfigureServices(IServiceCollection services)
{
//....
//....
services.AddSingleton<IMyService,MyService>();
var serviceProvider = services.BuildServiceProvider();
var myService = serviceProvider.GetService<IMyService>();
services.AddDbContext<MyDbContext>(options => options.UseMySql(myService.DBConnectionString));
}
Run Code Online (Sandbox Code Playgroud)
上面的代码对我来说很好用,可以在 ConfigureServices 中使用“MyService”。但是稍后在我的应用程序中,当我尝试使用 MyService 时,将再次调用 MyService 的构造函数。为什么不使用自我使用注册类以来已经创建的实例AddSingleton?
编辑:我决定编辑以添加我的最终目标,看看是否有不同的方法来完成它。我的单例服务提供对一些可能来自 2 个不同地方的设置的访问。这些设置之一是数据库连接字符串。我在 ConfigureServices 中需要那个连接字符串,所以当我调用services.AddDbContext. 我还想在获取配置设置的服务中进行一些日志记录,这意味着我还需要获取 ILoggerFactory。