0

我制作了一个能够更改其 app.config(连接字符串部分)的应用程序。我尝试了几种解决方案,事实证明这是解决我的一个问题的最简单方法。这是我使用的代码:

ConnectionStringSettings postavke = new ConnectionStringSettings("Kontrolor.Properties.Settings.KontrolorConnectionString", constring);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Clear();
config.ConnectionStrings.ConnectionStrings.Add(postavke);   

config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName);

此代码放置在 button_click 方法中,当我单击该按钮并重新启动应用程序时,更改是可见的。我的问题是这个 - 有没有办法从另一个(独立)应用程序中做到这一点,使用户能够通过在文本框中输入所需的值或从组合框中选择它来创建连接字符串(他只需要输入 IP服务器和数据库的名称)。通过这样做,第一个应用程序将被预先准备好,不需要重新启动它来应用更改。有没有办法做到这一点?

4

1 回答 1

1

由于两个应用程序都在同一台机器上,您可以使用简单的 windows 消息传递,在两个应用程序中注册 windows 消息并将发送者发布消息到接收者,这里是示例代码:

发件人:

  public partial class FormSender : Form
  {
    [DllImport("user32")]
    private static extern int RegisterWindowMessage(string message);

    private static readonly int WM_REFRESH_CONFIGURATION = RegisterWindowMessage("WM_REFRESH_CONFIGURATION");

    [DllImport("user32")]
    private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

    public FormSender()
    {
      InitializeComponent();
    }

    private void btnNotify_Click(object sender, EventArgs e)
    {
      NotifyOtherApp();
    }

    private void NotifyOtherApp()
    {
      List<Process> procs = Process.GetProcesses().ToList();
      Process receiverProc = procs.Find(pp => pp.ProcessName == "Receiver" || pp.ProcessName == "Receiver.vshost");  
      if (receiverProc != null)
        PostMessage((IntPtr)receiverProc.MainWindowHandle, WM_REFRESH_CONFIGURATION, new IntPtr(0), new IntPtr(0));
    }
  }

接收者 :

 public partial class FormReceiver : Form
  {
    [DllImport("user32")]
    private static extern int RegisterWindowMessage(string message);

    private static readonly int WM_REFRESH_CONFIGURATION = RegisterWindowMessage("WM_REFRESH_CONFIGURATION");

    public FormReceiver()
    {
      InitializeComponent();
    }

    protected override void WndProc(ref Message m)
    {
      if (m.Msg == WM_REFRESH_CONFIGURATION)
      {
        lblMessageReceived.Text = "Refresh message recevied : " + DateTime.Now.ToString();
      }
      else
      {
        base.WndProc(ref m);
      }
    }
  }

顺便提一句。请注意,我正在检查进程名称“Receiver.vshost”,以便它在 VS 调试器中启动时可以工作

于 2012-04-16T12:43:18.077 回答