WinForms: topmost form loses focus on hiding dialog called from it - forms

I have a WinForms project with a main topmost form from which a non-modal dialog is displayed. I need to hide (not close) the dialog if it loses the input focus - no matter what was the reason (the user clicked the main form, switched to another app, etc). The following bare part of the project source code shows what is going on:
public partial class MainForm : Form
{
Form _dialog = new Form();
public MainForm()
{
InitializeComponent();
this.TopMost = true;
this.Text = "Main Form";
_dialog.Text = "Dialog";
_dialog.Owner = this;
_dialog.TopMost = true;
_dialog.Deactivate += Dialog_Deactivate;
_dialog.FormClosing += Dialog_FormClosing;
}
private void Dialog_Deactivate(object sender, EventArgs e)
{
_dialog.Hide();
}
private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
{
_dialog.Hide();
e.Cancel = true;
}
private void ButtonShowDialog_Click(object sender, EventArgs e)
{
_dialog.Show();
}
}
The main problem I am trying to solve is the following. If the user opened the dialog and clicks the main form like I depicted on the following screenshot
, the dialog becomes hidden as expected, but the main form loses the focus and another app that was previously active becomes active in the background - the Windows Explorer on the next screenshot:
Is it a known issue in Windows or WinForms? How to cause the main form not to lose the focus in this construction?

The issue seems to be that when the Main Form is clicked, it triggers a WM_WINDOWPOSCHANGING event. Since the child dialog is open, the hwndInsertAfter handle is the child dialog. But then in the Dialog_Deactivate the child dialog is hidden, causing the Main Form to fall behind all the other windows because the hwndInsertAfter handle is no longer a visible window.
Possible solutions are 1) set the child dialog owner to null before calling Hide() or 2) use a different event, like LostFocus, i.e:
public class MainForm3 : Form {
Form _dialog = null;
public MainForm3() {
this.Text = "Main Formmmmmmmm";
Button btn = new Button { Text = "Show" };
btn.Click += ButtonShowDialog_Click;
this.Controls.Add(btn);
}
bool b = false;
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (_dialog != null && _dialog.Visible)
b = true;
if (b)
Debug.WriteLine(m);
int WM_WINDOWPOSCHANGING = 0x46;
if (b && m.Msg == WM_WINDOWPOSCHANGING) {
var wp = Marshal.PtrToStructure<WINDOWPOS>(m.LParam);
Debug.WriteLine("hwnd: " + wp.hwnd + " " + GetWindowText(wp.hwnd));
Debug.WriteLine("hwndInsertAfter: " + wp.hwndInsertAfter + " " + GetWindowText(wp.hwndInsertAfter));
Debug.WriteLine("flags: " + wp.flags);
}
}
private void Dialog_Deactivate(object sender, EventArgs e) {
_dialog.Owner = null; // solution 1
_dialog.Hide();
}
private void _dialog_LostFocus(object sender, EventArgs e) { // solution 2
_dialog.Hide();
}
private void Dialog_FormClosing(object sender, FormClosingEventArgs e) {
if (_dialog.Visible) {
_dialog.Hide();
e.Cancel = true;
}
}
private void ButtonShowDialog_Click(object sender, EventArgs e) {
if (_dialog == null) {
_dialog = new Form();
_dialog.Text = "Dialoggggggg";
//_dialog.Deactivate += Dialog_Deactivate;
_dialog.LostFocus += _dialog_LostFocus; // solution 2, use LostFocus instead
_dialog.FormClosing += Dialog_FormClosing;
}
_dialog.Owner = this;
_dialog.Show();
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPOS {
public IntPtr hwnd, hwndInsertAfter;
public int x, y, cx, cy;
public SWP flags;
}
[Flags]
public enum SWP : uint {
SWP_ASYNCWINDOWPOS = 0x4000,
SWP_DEFERERASE = 0x2000,
SWP_DRAWFRAME = 0x0020,
SWP_FRAMECHANGED = 0x0020,
SWP_HIDEWINDOW = 0x0080,
SWP_NOACTIVATE = 0x0010,
SWP_NOCOPYBITS = 0x0100,
SWP_NOMOVE = 0x0002,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOREDRAW = 0x0008,
SWP_NOREPOSITION = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
SWP_NOSIZE = 0x0001,
SWP_NOZORDER = 0x0004,
SWP_SHOWWINDOW = 0x0040
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
private static String GetWindowText(IntPtr hWnd) {
StringBuilder sb = new StringBuilder(256);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
}

Try calling Activate() on the main form after the dialog is hidden, i.e:
private void Dialog_Deactivate(object sender, EventArgs e)
{
_dialog.Hide();
this.Activate();
}

Related

State Management (Session)

I have one listBox named lstKosnicka and one ADD button named btnDodadi.
protected void btnDodadi_Click(object sender, EventArgs e)
{
DodadiVoKosnicka kosnicka = new DodadiVoKosnicka();
ListItem stavka = new ListItem();
List<ListItem> lista = new List<ListItem>();
stavka = kosnicka.novaStavka(lstPredlog.SelectedItem.Text);
lstKosnicka.DataSource = Session["kosnicka"] as List<ListItem>;
lstKosnicka.Items.Add(stavka);
lstKosnicka.DataBind();
Session["kosnicka"] = lstKosnicka;
lstPredlog.SelectedIndex = -1;
}
There is one more webForm with other listbox named lstKosnickaNajava, and I want to fill this list wtih the same items as lstKosnicka using Session["kosnicka"], but something is wrong. here is Najava.aspx code:
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie kolace = Request.Cookies["korisnik"];
if (kolace != null)
{
lblNajavenKorisnik.Text = "Најавен коринсик " + kolace["KorisnickoIme"];
}
else
{
lblNajavenKorisnik.Text = "Нема најавени корисници";
}
if (!IsPostBack)
{
lstKosnickaNajava.DataSource = Session["kosnicka"] as List<ListItem>;
lstKosnickaNajava.DataBind();
}
}
but when I go from the first page to Najava.aspx the lstKosnickaNajava is empty.
Maybe you should try in btnDodadi_Click()
this code
List<string> lista;
if (Session["kosnicka"] == null)
{
lista = new List<string>();
}
else
{
lista=(List<string>)Session["kosnicka"];
}
if you add only text the list item can be string.
I forget to ask maybe you do this in PAge_Load method??

Instance-Specific EventHandler to provide data visibility beyond the Class-Level

May I ask for help with the following?
I am attempting to connect and control three pieces of household electronic equipment by computer through a GlobalCache GC-100 and iTach. As you will see in the following code, I created a class ("GlobalCacheAdapter") that can communicate and control the equipment, and created an instance of the class for each piece of equipment. Although each instance seems to work well with communicating and in controlling each piece of equipment, the *feedback returned from the equipment* seems only to be visible at the defining class level's - "ReaderThreadProc" procedure. Further processing of the feedback is required for each piece of equipment and I am uncertain as to how to forward this feedback at the equipment specific instance-level. I suspect that an instance-specific EventHandler will need to be implemented; however I am not aware as to how to implement this type of instance-specific EventHandler in order to complete processing and update the appropriate controls.
Any help wold be greatly appreciated.
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Create three new instances of GlobalCacheAdaptor and connect.
// GC-100 (Elan) 192.168.1.70 4998
// GC-100 (TuneSuite) 192.168.1.70 5000
// GC iTach (Lighting) 192.168.1.71 4999
private GlobalCacheAdaptor elanGlobalCacheAdaptor;
private GlobalCacheAdaptor tuneSuiteGlobalCacheAdaptor;
private GlobalCacheAdaptor lutronGlobalCacheAdaptor;
public Form1()
{
InitializeComponent();
elanGlobalCacheAdaptor = new GlobalCacheAdaptor();
elanGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 4998);
tuneSuiteGlobalCacheAdaptor = new GlobalCacheAdaptor();
tuneSuiteGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 5000);
lutronGlobalCacheAdaptor = new GlobalCacheAdaptor();
lutronGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.71"), 4999);
elanTextBox.Text = elanGlobalCacheAdaptor._line;
tuneSuiteTextBox.Text = tuneSuiteGlobalCacheAdaptor._line;
lutronTextBox.Text = lutronGlobalCacheAdaptor._line;
}
private void btnZoneOnOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,4,1,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,800" + Environment.NewLine); }
private void btnSourceInput1_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,179,20,179,20,179,20,179,20,179,20,179,20,179,20,278,20,179,20,179,20,179,20,780" + Environment.NewLine); }
private void btnSystemOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,184,20,184,20,184,20,184,20,184,20,286,20,286,20,286,20,184,20,184,20,184,20,820" + Environment.NewLine); }
private void btnLightOff_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,0,0,S2\x0d"); }
private void btnLightOn_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,100,0,S2\x0d"); }
private void btnChannel31_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x31\x00\x30\x21\xB8\x0D"); }
private void btnChannel30_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x30\x00\x30\x21\xB8\x0D"); }
}
}
public class GlobalCacheAdaptor
{
public Socket _multicastListener;
public string _preferredDeviceID;
public IPAddress _deviceAddress;
public Socket _deviceSocket;
public StreamWriter _deviceWriter;
public bool _isConnected;
public int _port;
public IPAddress _address;
public string _line;
public GlobalCacheAdaptor() { }
public static readonly GlobalCacheAdaptor Instance = new GlobalCacheAdaptor();
public bool IsListening { get { return _multicastListener != null; } }
public GlobalCacheAdaptor ConnectToDevice(IPAddress address, int port)
{
if (_deviceSocket != null) _deviceSocket.Close();
try
{
_port = port;
_address = address;
_deviceSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_deviceSocket.Connect(new IPEndPoint(address, port)); ;
_deviceAddress = address;
var stream = new NetworkStream(_deviceSocket);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true };
_deviceWriter = writer;
writer.WriteLine("getdevices");
var readerThread = new Thread(ReaderThreadProc) { IsBackground = true };
readerThread.Start(reader);
_isConnected = true;
return Instance;
}
catch { DisconnectFromDevice(); MessageBox.Show("ConnectToDevice Error."); throw; }
}
public void SendMessage(string message)
{
try
{
var stream = new NetworkStream(_deviceSocket);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true };
_deviceWriter = writer;
writer.WriteLine(message);
var readerThread = new Thread(ReaderThreadProc) { IsBackground = true };
readerThread.Start(reader);
}
catch { MessageBox.Show("SendMessage() Error."); }
}
public void DisconnectFromDevice()
{
if (_deviceSocket != null)
{
try { _deviceSocket.Close(); _isConnected = false; }
catch { MessageBox.Show("DisconnectFromDevice Error."); }
_deviceSocket = null;
}
_deviceWriter = null;
_deviceAddress = null;
}
**private void ReaderThreadProc(object state)**
{
var reader = (StreamReader)state;
try
{
while (true)
{
var line = reader.ReadLine();
if (line == null) break;
_line = _line + line + Environment.NewLine;
}
**// Feedback from each piece of equipment is visible here.
// Need to create EventHandler to notify the TextBoxes to update with _line**
}
catch { MessageBox.Show("ReaderThreadProc Error."); }
}
}
From my understanding of the question, you want to do something like this?
You need to know when a GlobalCacheAdapter updates and which one updated in order to update textboxes on a form. My question to you is this - do you actually need to know which updated?
If you declare in your class an event handler like this:
public class GlobalCacheAdaptor
{
public event EventHandler<EventArgs> Updated;
protected virtual void OnUpdated()
{
var handler = Updated;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
private void Foo()
{
// When an update is received, raise Updated event
OnUpdated();
}
}
Then in your form subscribe to Updated for all three GlobalCacheHandler instances
public Form1()
{
elanGlobalCacheAdaptor.Updated += (s,e) =>
{
elanTextBox.Text = elanGlobalCacheAdaptor._line;
}
tuneSuiteGlobalCacheAdaptor.Updated += (s,e) =>
{
tuneSuiteTextBox.Text = tuneSuiteGlobalCacheAdaptor._line;
}
lutronGlobalCacheAdaptor.Updated += (s,e) =>
{
lutronTextBox.Text = lutronGlobalCacheAdaptor._line;
}
}
You should be able to update the correct text box when the appropriate cache handler raises the Updated event.
Finally you may need to handle cross-thread interactions. if so, see this article on MSDN, particularly the part "Thread-Safe Calls to a Windows Forms Control"

Why not work drag and drop?

I need drag from window1.listbox drop in window2.panel.
A write:
public partial class Form1 : Form
{
Routers r = new Routers();
public Form1()
{
InitializeComponent();
r.Show();
panel1.DragOver += new DragEventHandler(panel1_DragOver);
panel1.DragEnter += new DragEventHandler(panel1_DragEnter);
panel1.MouseUp += new MouseEventHandler(panel1_MouseUp);
panel1.DragDrop += new DragEventHandler(panel1_DragDrop);
panel1.AllowDrop = true;
this.AllowDrop = true;
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragDrop(object sender, DragEventArgs e)
{
throw new NotImplementedException();
}
void panel1_DragDrop(object sender, DragEventArgs e)
{
if (isDrop == false)
{
isDrop = true;
Button b = new Button();
b.Text = (string)e.Data.GetData(DataFormats.StringFormat);
b.Location = new Point(e.X, e.Y);
this.panel1.Controls.Add(b);
}
}
void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (isDrop)
{
isDrop = false;
}
}
bool isDrop = false;
void panel1_DragEnter(object sender, DragEventArgs e)
{
isDrop = false;
if (e.Data.GetDataPresent(DataFormats.StringFormat))
e.Effect = DragDropEffects.None;
}
void panel1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.None;
}
}
write window2
public partial class Routers : Form
{
public Routers()
{
InitializeComponent();
this.listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
this.listBox1.DragOver += new DragEventHandler(listBox1_DragOver);
}
private void listBox1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (this.listBox1.SelectedItem != null)
{
string item = this.listBox1.SelectedItem.ToString();
this.listBox1.DoDragDrop(item, DragDropEffects.Move);
}
}
}
DragDrop event not work.
and does not change the cursor when dragging
You need to set e.Effect to something other than None when dragging over the destination.
See this topic for the solution:
DragDrop event not raised
private void Form1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}

Problem with GWT connector in a straight ended connection

I am trying to make a straight ended connection between widgets.But when I am doing so, the orientation of my connector is coming wrong.Its always coming parallel to the required one.Also , it is independent of the connecting widgets i.e when I move my widget, my connector does not move.Snippet of my code is given as :
Link to snapshot of the problem: http://goo.gl/JUEmJ
public class DragNDropPage {
SyncCurrentUser cu = SyncCurrentUser.getUser();
private AbsolutePanel area = new AbsolutePanel();
HorizontalPanel toolsPanel = new HorizontalPanel();
AbsolutePanel canvas = new AbsolutePanel();
DragController toolboxDragController;
Label startLabel = new Label("START");
Label stopLabel = new Label("STOP");
Label activityLabel = new Label("ACTIVITY");
Label processLabel = new Label("PROCESS");
Button stopDrag = new Button("Done Dragging");
Button saveButton = new Button("Save");
PickupDragController dragController = new PickupDragController(area, true);
AbsolutePositionDropController dropController = new AbsolutePositionDropController(area);
private List<Widget> selected = new ArrayList<Widget>();
private List<Widget> onCanvas = new ArrayList<Widget>();
private List<Connection> connections = new ArrayList<Connection>();
private CActivity[] aItems;
private CProcess[] pItems;
MyHandler handler = new MyHandler();
int mouseX,mouseY;
String style;
public DragNDropPage() {
toolboxDragController = new ToolboxDragController(dropController, dragController);
RootPanel.get("rightbar").add(area);
area.setSize("575px", "461px");
area.add(toolsPanel);
toolsPanel.setSize("575px", "37px");
toolsPanel.add(startLabel);
startLabel.setSize("76px", "37px");
toolboxDragController.makeDraggable(startLabel);
toolsPanel.add(stopLabel);
stopLabel.setSize("66px", "37px");
toolboxDragController.makeDraggable(stopLabel);
toolsPanel.add(activityLabel);
activityLabel.setSize("82px", "36px");
toolboxDragController.makeDraggable(activityLabel);
toolsPanel.add(processLabel);
processLabel.setSize("85px", "36px");
toolboxDragController.makeDraggable(processLabel);
stopDrag.addClickHandler(handler);
toolsPanel.add(stopDrag);
stopDrag.setWidth("114px");
saveButton.addClickHandler(handler);
toolsPanel.add(saveButton);
area.add(canvas, 0, 36);
canvas.setSize("575px", "425px");
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
//46 is the key code for Delete Button
if(event.getNativeEvent().getKeyCode() == 46 && !selected.isEmpty()) {
for (Iterator<Widget> i = selected.listIterator(); i.hasNext();) {
Widget w = (Widget) i.next();
UIObjectConnector.unwrap(w);
i.remove();
w.removeFromParent();
onCanvas.remove(i);
}
}
}
});
aItems = cu.currentUser.getcActivity();
pItems = cu.currentUser.getcProcess();
}
private class ToolboxDragController extends PickupDragController {
public ToolboxDragController(final DropController dropController, final DragController nodesDragController) {
super(area ,false);
setBehaviorDragProxy(true);
registerDropController(dropController);
addDragHandler(new DragHandlerAdapter(){
public void onPreviewDragEnd(DragEndEvent event) throws VetoDragException {
Widget node = (Widget) event.getSource();
int left = event.getContext().desiredDraggableX;
int top = event.getContext().desiredDraggableY;
AbsolutePanel panel = (AbsolutePanel) dropController.getDropTarget();
createConnector((Label) node, panel, left, top);
throw new VetoDragException();
}
});
}
}
protected UIObjectConnector createConnector(Label proxy, AbsolutePanel panel, int left, int top) {
Widget w;
String str = proxy.getText();
if(str.equals("START") || str.equals("STOP")){
w = new Label(proxy.getText()){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
w.getElement().setClassName("dnd-start-stop");
}
else{
w = new ListBox(){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
if(str.equals("ACTIVITY")){
getAItems((ListBox)w);
//w.getElement().addClassName("dnd-activity");
}
else if(str.equals("PROCESS")){
getPItems((ListBox)w);
//w.getElement().addClassName("dnd-process");
}
}
onCanvas.add(w);
left -= panel.getAbsoluteLeft();
top -= panel.getAbsoluteTop();
//panel.add(w,10,10);
panel.add(w, left, top);
dragController.makeDraggable(w);
return UIObjectConnector.wrap(w);
}
private void getAItems(ListBox w) {
for(int i=0;i<aItems.length;i++)
w.addItem(aItems[i].getActivityName());
}
private void getPItems(ListBox w) {
/*for(int i=0;i<pItems.length;i++)
w.addItem(pItems[i].getProcessName());*/
w.addItem("Process1");
}
protected void select(Widget w){
if(selected.isEmpty()) {
selected.add(w);
w.getElement().addClassName("color-green");
} else if(selected.contains(w)){
selected.remove(w);
w.getElement().removeClassName("color-green");
} else if(selected.size() == 1) {
Widget w2 = (Widget) selected.get(0);
connect(UIObjectConnector.getWrapper(w2), UIObjectConnector.getWrapper(w));
selected.clear();
}
}
protected void connect(Connector a, Connector b) {
//System.out.println(a.getLeft());
//System.out.println(b.getLeft());
add(new StraightTwoEndedConnection(a,b));
}
private void add(StraightTwoEndedConnection c) {
canvas.add(c);
connections.add(c);
c.update();
}
protected void remove(Connection c) {
connections.remove(c);
}
class MyHandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
Button name = (Button) event.getSource();
if(name.equals(stopDrag)){
if(name.getText().equals("Done Dragging")){
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeNotDraggable(w);
}
name.setText("Continue");
}
else {
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeDraggable(w);
}
name.setText("Done Dragging");
}
}
else{
}
}
}
}
I know this is quite old, but I was having similar issues with the gwt-connector library.
The connectors will not appear in the correct placement if you are using standards mode. Use quirks mode instead.
Additionally, you need to manually perform a connector.update() while your dnd components are being dragged (in your drag listener) for the connection to move with the endpoint while you are dragging.

Listen to msmq queue

Following the is the code I have for listening to messages from Windows form.
I have noticed that when I click on send it sends a message to MyQueue but at that time I was hoping the event mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) should get called but it is not, in other words I am trying to subscribe to MyQueue from Windows form. Just wondering if I am missing something in the code:
public class Form1 : System.Windows.Forms.Form
{
public System.Messaging.MessageQueue mq;
public static Int32 j=0;
public Form1()
{
// Required for Windows Form Designer support
InitializeComponent();
// Queue Creation
if(MessageQueue.Exists(#".\Private$\MyQueue"))
mq = new System.Messaging.MessageQueue(#".\Private$\MyQueue");
else
mq = MessageQueue.Create(#".\Private$\MyQueue");
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
mq.BeginReceive();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnMsg_Click(object sender, System.EventArgs e)
{
// SendMessage(Handle, 1, 0, IntPtr.Zero);
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = txtMsg.Text;
mm.Label = "Msg" + j.ToString();
j++;
mq.Send(mm);
}
void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void btnRcv_Click(object sender, System.EventArgs e)
{
System.Messaging.Message mes;
string m;
try
{
mes = mq.Receive(new TimeSpan(0, 0, 3));
mes.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});
m = mes.Body.ToString();
}
catch
{
m = "No Message";
}
MsgBox.Items.Add(m.ToString());
}
}
See MSDN's example on how to use the ReceiveCompletedEventHandler .
They have a console app where the Main() does the same as your Form1(), but your handler doesn't have any code. You've said it doesn't call back into your event delegate, but perhaps check your queue name is correct on the constructor.
Consider using MSDN's sample code in a new console app to test your environment first, then go back to your WinForms code with any lessons learned.
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message: " + (string)m.Body);
mq.BeginReceive();
return;
}
If you want to inspect the queue and get a message on the click of a button, you can simply move the statement mq.BeginReceive(); to the btnRcv_Click() in place of .Receive();