public static void Unregister(int instanceId, IntPtr serviceHandle) { // This method could be called by the GC finalizer thread. If it is then a direct call to the DDEML will fail since the DDEML is // thread specific. A message will be posted to the DDEML thread instead. lock (_Table) { if (_Table.ContainsKey(serviceHandle)) { // Determine if the current thread matches what is in the table. int threadId = (int)_Table[serviceHandle]; if (threadId == Ddeml.GetCurrentThreadId()) { // Unregister the service name. Ddeml.DdeNameService(instanceId, serviceHandle, IntPtr.Zero, Ddeml.DNS_UNREGISTER); // Free the service string handle. Ddeml.DdeFreeStringHandle(instanceId, serviceHandle); } else { // Post a message to the thread that needs to execute the Ddeml.DdeXXX methods. PostThreadMessage(threadId, WM_APP + 3, new IntPtr(instanceId), serviceHandle); } // Remove the service handle from the table because it is no longer in use. _Table.Remove(serviceHandle); } } }
public static IntPtr Register(int instanceId, string service) { lock (_Table) { // Create a string handle for the service name. IntPtr serviceHandle = Ddeml.DdeCreateStringHandle(instanceId, service, Ddeml.CP_WINANSI); // Register the service name. IntPtr result = Ddeml.DdeNameService(instanceId, serviceHandle, IntPtr.Zero, Ddeml.DNS_REGISTER); if (result != IntPtr.Zero) { // Make sure this thread has an IMessageFilter on it. LocalDataStoreSlot slot = Thread.GetNamedDataSlot(DataSlot); if (Thread.GetData(slot) == null) { RegistrationManager filter = new RegistrationManager(); Application.AddMessageFilter(filter); Thread.SetData(slot, filter); } // Add an entry to the table that maps the service handle to the current thread. _Table.Add(serviceHandle, Ddeml.GetCurrentThreadId()); } else { // Free the string handle created earlier. Ddeml.DdeFreeStringHandle(instanceId, serviceHandle); serviceHandle = IntPtr.Zero; } return serviceHandle; } }
bool IMessageFilter.PreFilterMessage(ref Message m) { if (m.Msg == WM_APP + 3) { // Unregister the service name. Ddeml.DdeNameService(m.WParam.ToInt32(), m.LParam, IntPtr.Zero, Ddeml.DNS_UNREGISTER); // Free the service string handle. Ddeml.DdeFreeStringHandle(m.WParam.ToInt32(), m.LParam); } return false; }