|
You could just try listening for the MouseMove event and check to see if the mouse is still within the child form. It would be another option if you can't get the MouseLeave to behave properly.
|
|
|
|
|
I tried doing that, but the event is not triggered at all. If it is, I can filtrate it -- I can determine whether the cursor is on the child's area or not. Do you have anything in particular in mind? How should I trigger the event? That is the main problem.
|
|
|
|
|
It sounded kind of interesting that you couldn't get that to work, so I tried it out. It works using MouseLeave and Capture.
Try the following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Form f = new Form())
{
f.Capture = true;
f.MouseLeave += new EventHandler(f_MouseLeave);
f.Location = new Point(Control.MousePosition.X - 50, Control.MousePosition.Y - 50);
f.ShowDialog(this);
}
}
private void f_MouseLeave(object sender, EventArgs e)
{
MessageBox.Show("Left child.");
((Form)sender).Close();
}
}
Btw, the mouse position is in screen coordinates, so you should convert it if you're wanting to see if its still within the child form (if you had gone that route).
Point pointRelativeToForm = f.PointToClient(Control.MousePosition);
|
|
|
|
|
Btw, after refreshing myself on the usage of Capture[^], you don't use that but in drag operations normally. So, you don't need to set it.
|
|
|
|
|
|
Good day everyone,
I am working on a project and I am having a few issues.
Project detail
1. Am trying to simulate a RIP based router in Windows
2. I am developing this in C#
3. Am using Winpcap and SharpCap
4. So far I have figured out what my routing table would look like
My issues are as follows
1. Initially when RIP starts it sends a request packet out all RIP enabled interfaces
on IP address 255.255.255.255
I have tried to simulate this directly but decided to let .NET manage the packet
header creation, so what i have done is simply to send "Type 1 message" as
the payload and when the receiving router sees this it knows it should send its routes.
This is not how it should be done, but i guess i can work with this for now, as I can't
seem to be able to create my own packet header in C# easily.
Any suggestions on how best I can create a packet without doing low level stuffs would be
appreciated or any library i can simply reference that just accepts port number, ip addresses,
payload and returns a packet as response?
2. After sending I should wait for response from other Routers.
These received packets are called Response Packets and contain the responding routers'
routes.
To do this i have decided that after the Request is sent out all interfaces, I would wait for about
25sec for responses.
Issue: I do not know how best to implement this, I have tried editting the Sample Codes in sharpCap
and also tried socket.listen method
but I can't tell if anything is coming in or not.
3. I installed WireShark to help me detect if I am even sending anything out the interfaces in the first place
and it appears am not, as wireshark does not report anything. And yes I selected the right interface.
So any help please.
Below is a cut out of my code so far
...
ArrayList ripIntefaces;
public void start(int[] deviceIndex)
{
//get list of intefaces again
var devices = LivePcapDeviceList.Instance;
//send request out all RIP enabled interfaces
for (int k = 0; k < deviceIndex.Length; k++)
sendRequestsInitial(devices[deviceIndex[k]]);
//wait 4 response
while (true)
{
//1st time around dont run infinitively, just capture n close
for (int k = 0; k < deviceIndex.Length; k++)
receiveResponse(ripIntefaces, deviceIndex); //this should be threaded 4 listening on each interface
}
}
....
private void sendRequestsInitial(LivePcapDevice enabledIntf)
{
string nxtHop = enabledIntf.Addresses[1].Addr.ipAddress.ToString(); //should be but I cant bind ip add "255.255.255.255";
int portNo = 520;
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPAddress sendTo = IPAddress.Parse(nxtHop);
IPEndPoint sEndPoint = new IPEndPoint(sendTo, portNo);
EndPoint sendEndPoint = (EndPoint)sEndPoint;
sock.Bind(sendEndPoint);
//create packet to send
byte[] pktContent = packetProcessor.makeRequestPacket();
sock.SendTo(pktContent,sendEndPoint);
}
....
private void receiveResponse(ArrayList ripNetworks, int[] deviceIndex)
{
//monitor all ripInterfaces
//start new thread 4 each - WORK ON
var devices = LivePcapDeviceList.Instance;
LivePcapDevice device = devices[deviceIndex[0]]; //testing 4 1 device 1st, others with thread
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
int readTimeoutMilliseconds = 25000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
device.StartCapture();
//device.Close();
}
...
private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
// myPacket tempPacket = new myPacket();
var packet = PacketDotNet.Packet.ParsePacket(e.Packet);
var ip = PacketDotNet.IpPacket.GetEncapsulated(packet);
var udp = PacketDotNet.UdpPacket.GetEncapsulated(packet);
string result = string.Empty;
if(ip != null)
{
if (udp != null)
{
result = Encoding.UTF8.GetString(udp.PayloadData);
}
}
Console.WriteLine(result);
}
....................
class packetProcessor
{
static byte[] packet;
public static byte[] makeRequestPacket()
{
string content = "Type 1 Message, Request";
packet = Encoding.ASCII.GetBytes(content);
return packet;
}
}
So any inputs??
|
|
|
|
|
The first question, if I use "using()" to open a connection,like this:
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(insertSQL);
command.Connection = connection;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
Whether I still need to use "connection.Close()" to close the object? Or it will be closed by .Net automatically?
Another question is, Whether "connection.open(),connection.close()" are necessary for a executing every time? For example, there is a querying in Form1.cs and a updating in Form2.cs, should I close the connection in whichever Form immediately ?
|
|
|
|
|
The using statement calls the destructor on the connection object, this will close the connection implicitly without the need to make an explicit call.
The answer to your second question is no. You need the connection to be open to execute anything on it, and your should close it when you are finished with it (the using clause does this for you as above.), between this you can execute multiple calls. For the most part open --> [single]execute --> close is considered good practise as the SQL server has a limited number of incoming connections, and it is good practice to be parsimonious with these. Under certain circumstances, you might want to keep the connection open to make multiple calls, but this is unlikely in your case.
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
Thanks. But I found a problem. Look my code.
public static OleDbDataReader GetData(string SQLstring)
{
using(OleDbConnection conn = new OleDbConnection(connstr)}
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(SQLstring, conn);
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
catch (SystemException e)
{
MessageBox.Show(e.Message);
return null;
}
}
}
public static OleDbDataReader GetData(string SQLstring)
{
OleDbConnection conn = new OleDbConnection(connstr);
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(SQLstring, conn);
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
catch (SystemException e)
{
MessageBox.Show(e.Message);
return null;
}
}
How to do?
|
|
|
|
|
There is a design principle that says that exceptions should be handled in the UI layer. (Strictly, they should be handled at the level where they can be appropriately resolved; when that resolution means simply telling the user that something is broken - reporting a message - that is the UI layer).
Your example method appears to belong in a data layer (given that it reads from a database; even if the method is actually in a Form, functionally the work of the method is data layer behavior).
According to the design principle, your method should not be handling the exception but allowing a method 'closer to the user' to handle it ... by making its report to the user. If you change your code to do this, then you don't have to be concerned with whether a null is returned for the OleDbDataReader - under non-exception conditions (which is the only time you care) it is guaranteed to be non-null.
So, your method could be simplified to:
public static OleDbDataReader GetData(string SQLstring)
{
using (OleDbConnection conn = new OleDbConnection(connstr))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(SQLstring, conn);
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
}
... and you would put your try/catch around (the call to...) the call to GetData().
A guideline to help with deciding whether to put try/catch inside a method is to ask yourself whether, by using try/catch, you can ensure that the behavior described by the method name is performed. In the case of GetData() the try/catch did not ensure that data would be available under all circumstances: it fails the test in the guideline and indicates that the try/catch belongs elsewhere.
Further up the call stack there is probably an event handler ("DataLoadButton_ClickEvent()", or some such). Reporting 'couldn't get data' is a valid and complete handling of a button click event, so it passes the test in the guideline and is a valid place for a try/catch.
It is important to be clear about the purpose of methods. A button click event handler (such as DataLoadButton_ClickEvent()) can seem to be about loading data. That is misleading. The event handler is about handling the event; one way to handle the event is to load data, but another, equally valid, way to handle the event is to say "I couldn't." And it just so happens that the design of languages with structured exception handling (in this case, C#) allows for the 'loading data' behavior to be coded as the 'normal' or non-exceptional path and the 'I couldn't' behavior to be treated as exceptional - allowing the flow of the normal path to be easier to read for us humans by relegating the exceptional behavior to the catch{} block.
|
|
|
|
|
Your suggestions are so useful to me. I've really learn a lot, thank you!
|
|
|
|
|
Hey Keith, OleDbConnection does not have a destructor (Reflectoring shows no Finalize method), only a Dispose
|
|
|
|
|
OleDbConnection.Dispose (used by using ) does this.Close() (among other things)
So you shouldn't need to call Close manually.
|
|
|
|
|
|
The Dispose will call the Close, but I suggest calling Close from a finally anyway.
But Personally, I wouldn't use a using statement in this case. I'd instantiate the Connection in the Form's Load handler (or similar) and Close/Dispose it in the Form's Closing handler (or similar) so the Connection gets reused.
|
|
|
|
|
|
thanx to this discussion i gained a lot but at the same time i tried to simulate this , and found that you can return the datareader but cannot use it , means after the using {} is finished the connection is no longer open and you cannot read data through the datareader returned by this connection.
datreader doesn't buffer data too, so you cannot get data by this...to get data the connection should be opened..
|
|
|
|
|
That's right. So I do not use "using" if I want to return the datareader.
But "CommandBehavior.CloseConnection" is a remedy for this.
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Once you close datareader, the connection will be closed too. You can see this result in step debugging.
|
|
|
|
|
I use Speech component and when speaker is reading, the other commands not work, how can i enable pause and stop during speaking?
thanks everybody for the answers
|
|
|
|
|
Use the Speak command in a background worker so that nothing else is defunct till the speech is over.
|
|
|
|
|
so what shall i do?
use threads?
at micro programing it was so easy, just check a
flag or bit for an event each certain time.
but i can not found any thing in c#!
|
|
|
|
|
BackgroundWorker Component
Do you know about them?
What u hav 2 do is
Write the code to be executed in their DoWork event.
Then the play button should have code like BackgroundWorker1.RunWorkerAsync()
Read about BackgroundWorker. That is a simple and effective solution
|
|
|
|
|
hi
I want to insert the HTML tag in a page for c# ASP.net
thanks
|
|
|
|
|
|
What is your question?
It's time for a new signature.
|
|
|
|
|