我有两个名为app
和anotherapp
的应用程序以及一个类库myadp.dll
app
包含:
using myadp;
namespace app
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void bt_Click(object sender, RoutedEventArgs e)
{
Class1 c = new Class1();
tbinapp.Text = c.st;
}
}
}
anotherapp
包含:
using myadp;
namespace anotherapp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void anotherbt_Click(object sender, RoutedEventArgs e)
{
Class1 ad = new Class1();
ad.st = anothertb.Text;
}
}
}
myadp.dll
包含:
namespace myadp
{
public class Class1
{
public string st = "this is from adapter ";
}
}
我正在尝试使用anotherapp
作为适配器将值从app
传递到myadp
。但它没有用。我假设它不起作用,因为每个应用程序都在Class1
中创建类myadp
的新实例。我对吗?如何测试并修复它?
答案 0 :(得分:2)
最后它工作了(这里适配器的readfromnotepad()
正在返回记事本中编辑区的字符串)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
//using System.ServiceModel.Dispatcher;
namespace finally_adapter
{
public class adapt_
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
enum GetWindow_Cmd : uint {
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);
[DllImport("User32.dll")]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
int len;
public string strin;
const int WM_GETTEXT = 0x000D;
StringBuilder sb = new StringBuilder(100);
IntPtr hwnd;
public adapt_()
{
}
public string readfromnotepad()
{
string lpclassname = "Edit";
string lpwindowname = "Notepad";
int temp = FindWindow(lpwindowname,null);
hwnd = (IntPtr)temp;
StringBuilder temps = new StringBuilder(100);
IntPtr edit_hwnd = GetWindow(hwnd, GetWindow_Cmd.GW_CHILD);
IntPtr msg_hwnd = SendMessage(edit_hwnd, WM_GETTEXT, (IntPtr)100, temps);
return temps.ToString();
}
}
}
答案 1 :(得分:1)
你是正确的,每个应用程序都在创建Class1
的新实例,但它比这更深。您似乎误解了类如何在代码中工作的基本部分
共享命名空间myadp
的两个应用程序都可以在该命名空间中创建类Class1
,但这些类的实例不会在它们之间共享。
把它想象成两个孩子,每个孩子都有一套建造乐高屋的指示。使用他们拥有的块,他们可以构建相同的种的房子,但他们不是相同的房子。如果孩子A建房子,孩子B没有那个房子可以玩,他必须建立自己的房子。
要解决您的问题,您需要在某个地方存储数据,如数据库或公共方法,可以由另一个应用程序访问。