|
DateTime tm1 = ...;
DateTime tm2 = ...;
TimeSpan ts = tm2 - tm1;
System.Console.Writeln ("Difference in mins = " + ts.TotalMinutes); /ravi
|
|
|
|
|
When a user opens a file associated with your program you may want the new instance to pass along the file to the first instance and exit. One problematic way of doing this is using the Visaul Basic MainForm.Invoke and StartupNextInstanceEventHandler. However, this library won't work with MONO/Linux and for some reason it connects to the network while invoking the thread, triggering a nasty firewall popup.
Is there any C# alternative or is it possible to improve on the code to avoid the network and mono problems? Please and Thank you!
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
class Program
{
[STAThread]
static void Main(string[] args) { new App().Run(args); }
class App : WindowsFormsApplicationBase
{
public App()
{
IsSingleInstance = EnableVisualStyles = true;
ShutdownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses;
StartupNextInstance += new StartupNextInstanceEventHandler(NextInstance);
}
protected override void OnCreateMainForm()
{
MainForm = new Form1();
((Form1)MainForm).Args = new string[CommandLineArgs.Count];
CommandLineArgs.CopyTo(((Form1)MainForm).Args, 0);
}
protected void NextInstance(object sender, StartupNextInstanceEventArgs eventArgs)
{
string[] args = new string[eventArgs.CommandLine.Count];
eventArgs.CommandLine.CopyTo(args, 0);
MainForm.Invoke(new Form1.InstanceDelegate(((Form1)MainForm).processParameters), new object[] { MainForm, args });
}
}
}
public void processParameters(object sender, string[] args)
{
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
if (args != null && args.Length != 0)
openFiles(args);
}
// Mikzi L. Freeman
|
|
|
|
|
Mikzi, it is possible to pass objects around to other threads:
void FooBar(object state)
{
object[] thePassedObjects = (object[])state;
}
ThreadPool.QueueUserWorkItem(FooBar, new object[] {"hello", "world", "!"});
You can pass objects to the UI thread by calling the Invoke or BeginInvoke on some Control:
delegate void OurDelegate(string s, object o, int i);
void OurFunction(string s, object o, int i)
{
}
....
myControl.Invoke((OurDelegate)OurFunction, "hello", new object(), 5);
|
|
|
|
|
This seems like a simple implementation using invoke, but I'm unsure of how to get a handle to the main instance form without using VB.net MainForm.
static void Main(string[] args)
{
bool granted;
using (Mutex mutex = new Mutex(false, "mutexName", out granted))
{
if (granted) Application.Run(new Form1());
else xxx.Invoke(new Form1.InstanceDelegate(xxx.processParameters), new object[] { xxx, args });
}
}
// Mikzi L. Freeman
|
|
|
|
|
Hi!
In order to be able to invoke a method on the first instance's form you've got to have a reference to this form, of course.
One idea would be to let the first instance register a remoting server and the second instance access this remoting server.
Perhaps this is done internally in VB.NET's MainForm, it could explain the firewall message.
You could use the new (for .NET 2.0) ipc channel instead of a tcp channel, perhaps this doesn't trigger a firewall alert.
Regards,
mav
Regards,
mav
--
Black holes are the places where god divided by 0...
|
|
|
|
|
The client server method does work. It solves the problems with not relying on Visual Basic libraries as well as working with Mono/Linux. It requires some coding however, and it needs the ip address and a port number. Might be possible to simplify the process further than this...
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new App();
}
class App
{
private static Form1 mainform;
private Mutex mutex;
public App()
{
bool owned; int port = 1392;
mutex = new Mutex(false, "Form1", out owned);
if (!owned)
{
ChannelServices.RegisterChannel(new TcpChannel(), true);
string str = "tcp://" + Dns.GetHostEntry(Dns.GetHostName()).AddressList[0] + ":" + port + "/" + typeof(RemoteServer).GUID.ToString();
((RemoteServer)Activator.GetObject(typeof(RemoteServer), str)).ActivateInstance(Environment.GetCommandLineArgs());
}
else
{
ChannelServices.RegisterChannel(new TcpChannel(port), true);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteServer), typeof(RemoteServer).GUID.ToString(), WellKnownObjectMode.Singleton);
Application.Run(mainform = new Form1());
}
}
private class RemoteServer : MarshalByRefObject
{
public void ActivateInstance(string[] args)
{ args[0] = null; mainform.Invoke(new Form1.InstanceDelegate(((Form1)mainform).processParameters), new object[] { mainform, args }); }
}
}
// Mikzi L. Freeman
|
|
|
|
|
iwant to know the barcode font "the name of the bar code font"
|
|
|
|
|
|
I have a dll I'm coding in one solution, and a test project in another.
Does the referenced dll reloads in the test project, after recompiling the dll?
|
|
|
|
|
|
Partially, yes...
I don't want my dll to reference the test project.
I want my test project to reference the dll, and auto update every time I recompile the dll.
Is it possible?
|
|
|
|
|
|
And just delete the test project after I'm done coding the dll?
|
|
|
|
|
No need to delete it. Each project in your solution will build to different assemblies: your test project will build to an exe (assumedly) and your dll project will build to a seperate dll. When you're done building the dll, you just use the dll and ignore the test project. They'll get built into different assemblies and different directories, so there won't be any confusion about which files belong to which project.
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Messianic Instrumentals (with audio)
The apostle Paul, modernly speaking: Epistles of Paul
Judah Himango
|
|
|
|
|
Cool! Thanks!
|
|
|
|
|
Hello
I have to use a Win32 API in a C# project (VS 2K5). I want to create a API wrapper class in C++. And then use it from my C# code.
I tried to use P/Invoke in C# to create a wrapper class, some of the methods didn’t work because Pointers to memory were not working..
QUESTION 1
Now how do I create a wrapper class, save it as dll and use it in C#. Please tell me whole procedure.
Because when I try to create a C++ project The VS2005 gives me a list of templates to choose from like “CLR Console Application” “Windows Forms Application”, etc etc
Question 2
My project has a method that continuously reads a block of PCM data from an external radio receiver connected to the computer through USB.
Is there and way to listen to that signal through C#. IS PCM just like audio signal … if not how do I convert it into audio.
------------------------------------------------------------------------------------------------
I am writing an example of the function I have to write and tell me what type of project I have to make and what procedure I have to follow.
<br />
#include "stdafx.h"<br />
#include <stdio.h><br />
#include <windows.h><br />
<br />
typedef int (__stdcall *FNCOpenRadioDevice)(int iDeviceNum);<br />
typedef BOOL (__stdcall *FNCCloseRadioDevice)(int hRadio);<br />
typedef BOOL (__stdcall *FNCSetAtten)(int hRadio, BOOL fAtten);<br />
typedef BOOL (__stdcall *FNCSetPower)(int hRadio, BOOL fPower);<br />
typedef BOOL (__stdcall *FNCSetAGC)(int hRadio, int iAGC);<br />
typedef BOOL (__stdcall *FNCCodecStart)(int hRadio,void (__stdcall *CallbackFunc)(void *),<br />
void *CallbackTarget);<br />
typedef BOOL (__stdcall *FNCCodecStop)(int hRadio);<br />
typedef unsigned int (__stdcall *FNCCodecRead)(int hRadio,void *Buf,unsigned int Size);<br />
<br />
typedef struct {<br />
int hRadio;<br />
FILE *IFFile;<br />
FNCCodecRead CodecRead;<br />
} CallbackContext;<br />
<br />
void __stdcall CodecCallback(void *Target)<br />
{<br />
unsigned int i;<br />
char Buf[4096];<br />
CallbackContext *Ctx=(CallbackContext *)Target;<br />
<br />
while ((i=Ctx->CodecRead(Ctx->hRadio,Buf,sizeof(Buf)))!=0) <br />
fwrite(Buf,i,1,Ctx->IFFile);<br />
}<br />
int main(int argc, char* argv[])<br />
{<br />
HMODULE dll=LoadLibraryA("wrg303api.dll");<br />
if (!dll) {puts("WRG303API.DLL not found !"); return 0;}<br />
<br />
FNCOpenRadioDevice OpenRadioDevice=(FNCOpenRadioDevice)GetProcAddress(dll,"OpenRadioDevice");<br />
FNCCloseRadioDevice CloseRadioDevice=(FNCCloseRadioDevice)GetProcAddress(dll,"CloseRadioDevice");<br />
FNCSetAtten SetAtten=(FNCSetAtten)GetProcAddress(dll,"SetAtten");<br />
FNCSetPower SetPower=(FNCSetPower)GetProcAddress(dll,"SetPower");<br />
FNCSetAGC SetAGC=(FNCSetAGC)GetProcAddress(dll,"SetAGC");<br />
FNCCodecStart CodecStart=(FNCCodecStart)GetProcAddress(dll,"CodecStart");<br />
FNCCodecStop CodecStop=(FNCCodecStop)GetProcAddress(dll,"CodecStop");<br />
FNCCodecRead CodecRead=(FNCCodecRead)GetProcAddress(dll,"CodecRead");<br />
<br />
int hRadio=OpenRadioDevice(0);<br />
if (!hRadio) {puts("No WR-G303 device could be opened !");FreeLibrary(dll); return 0;}<br />
<br />
if (SetPower(hRadio,TRUE)) puts("The device is turned ON"); else puts("The device failed to turn ON");<br />
if (SetAtten(hRadio,FALSE)) puts("The attenuator is OFF"); else puts("The attenuator failed to turn OFF");<br />
if (SetAGC(hRadio,3)) puts("The AGC is FAST"); else puts("The AGC failed to switch");<br />
<br />
FILE *f=fopen("IF2.pcm","wb");<br />
<br />
CallbackContext Ctx;<br />
<br />
Ctx.hRadio=hRadio;<br />
Ctx.IFFile=f;<br />
Ctx.CodecRead=CodecRead;<br />
if (!CodecStart(hRadio,CodecCallback,&Ctx)) puts("Codec streaming couldn't be started!");<br />
else {<br />
puts("Codec streaming properly started!");<br />
while (!ftell(f) ) <br />
{<br />
}<br />
CodecStop(hRadio);<br />
fclose(f);<br />
}<br />
<br />
if (CloseRadioDevice(hRadio)) puts("The device is closed properly"); else puts("The device failed to close");<br />
<br />
FreeLibrary(dll);<br />
<br />
return 0;<br />
}<br />
o O º(`'·.,(`'·., ☆,.·''),.·'')º O o°
»·'"`»* *☆ t4ure4n ☆* *«·'"`«
°o O º(,.·''(,.·'' ☆`'·.,)`'·.,)º O o°
|
|
|
|
|
There's a great article over at MSDN[^] that goes over wrapping a native C++ library in the C++/CLI language. A C++/CLI dll can then be used in your C# or VB.NET projects simply by adding a reference to the dll inside Visual Studio (from Solution Explorer window, expand your C# project and right-click on the references item, then click Add Reference).
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Messianic Instrumentals (with audio)
The apostle Paul, modernly speaking: Epistles of Paul
Judah Himango
|
|
|
|
|
If i want to paint one cell in dataGridView. How do i do it.
dataGrid.Rows[count].Cells[1]
Suppose if i want to paint the whole cell as white or red how do it do it. Where dataGrid above is DataGridView
|
|
|
|
|
YoukalyanPaladugu wrote: if i want to paint the whole cell as white or red how do it do it
Derive a new type, a custom DataGridView cell. You can then control the painting yourself. Also, you might want to look at the cell's Paint event.
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Messianic Instrumentals (with audio)
The apostle Paul, modernly speaking: Epistles of Paul
Judah Himango
|
|
|
|
|
I used the below method to paint all the cells of the column in the datagridview but when i maximize and minimize the windows form
the effect of painting becomes bad. Any thoughts how to rectify that. Basically by the code below iam erasing the cells in the particular
column called col
void dataGridView1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
if (this.dataGridView1.Columns["Col"].Index == e.ColumnIndex && e.RowIndex >= 0)
{
using (
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
Rectangle newRect = new Rectangle(e.CellBounds.X +3,e.CellBounds.Y + 3, e.CellBounds.Width - 3, e.CellBounds.Height - 3);
e.Graphics.FillRectangle(backColorBrush, newRect);
e.Handled = true;
}
}
}
|
|
|
|
|
I don't know what the problem is, but I will say that just the other day another poster in this forum encountered problems while handling the dataGridView.CellPainting event. He got around his problem by just creating a custom cell type and overriding the painting himself.
|
|
|
|
|
I wanted to do the same thing and found some code
similar to what kalyanPaladugu posted in the msdn.
At least for me it seemed to work well.
I guess creating a custom cell type also has
its charme. I will use that idea when I want to do
a little more than just do some painting.
Thanks for the tip,
Erik
|
|
|
|
|
Hi
Sending objects over a wire from a client to a server. I 'serialise' the object on the client, send, via a Socket, and deserialise on server. Cool. Works a treat....for one object.
Whilst the server is handling the object I've sent, I might have sent three or four more, so when the server finally gets round to reading the socket stream again, it pulls in byte[] containing multiple serialised objects. Throwing that at my deserialise method fails. Do I have to manually tokensize the byte[] before sending and then on the server parse for the tokens? This could be a) slow as the tokens could be very large and b) not guarenteed, as the tokens I use could actually be part of the data in the serialised object, which would cause the deserialise to split in the wrong place.
Any ideas? Current code below
public void Go()
{
socket.BeginReceive(cs.RcvBuffer , 0 , cs.RcvBuffer.Length , SocketFlags.None , new AsyncCallback(ReadCallback), cs);
}
protected void ReadCallback(IAsyncResult ar)
{
clientState cs = (clientState)ar.AsyncState;
try
{
int recvMsgSize = cs.ClntSock.EndReceive(ar);
if (recvMsgSize > 0)
{
cs.TotalBytes += recvMsgSize;
Console.WriteLine("Thread {0} - ReadCallback(): total received {1} bytes",
ID,
cs.TotalBytes);
SocketTest.MyTestClass m = Decode(cs.RcvBuffer);
DoSomethingWithMyTestClass( m );
Go();
}
}
catch(SocketException se)
{
Console.WriteLine(se.ErrorCode + ":" + se.Message);
}
}
public SocketTest.MyTestClass Decode(byte[] theByteArray)
{
Console.WriteLine("Decoding {0} bytes", theByteArray.Length);
MemoryStream ms = new MemoryStream(theByteArray);
BinaryFormatter bf1 = new BinaryFormatter();
ms.Position = 0;
return (SocketTest.MyTestClass)bf1.Deserialize(ms);
}
Regards
Malc
*********************************************
|
|
|
|
|
Sorry, should have tried harder before posting....but it just clicked!
Easy - pass down the number of bytes recieved to the decode, and keep decoding until the position in the memorystream exceeds the number of bytes passed
New Code :
<br />
<br />
...snip....<br />
if (recvMsgSize > 0)<br />
{<br />
cs.TotalBytes += recvMsgSize;<br />
<br />
Console.WriteLine("Thread {0} - ReadCallback(): total received {1} bytes",<br />
ID,<br />
cs.TotalBytes);<br />
Decode(cs.RcvBuffer , recvMsgSize);<br />
<br />
<br />
public void Decode(byte[] theByteArray , long SizeOfBuffer)<br />
{<br />
Console.WriteLine("Decoding {0} bytes", SizeOfBuffer);<br />
MemoryStream ms = new MemoryStream(theByteArray);<br />
BinaryFormatter bf1 = new BinaryFormatter();<br />
ms.Position = 0;<br />
<br />
while (ms.Position < SizeOfBuffer)<br />
{<br />
SocketTest.Message m = (SocketTest.Message)bf1.Deserialize(ms);<br />
DoSomethingWithMyTestClass(m);<br />
}<br />
<br />
}<br />
<br />
<br />
<br />
Regards
Malc
*********************************************
|
|
|
|
|
You could add a header that contains the number of objects being transmitted and the size of each object in bytes. The tricky bit would be that since the number of objects being transmitted can vary, so too will the size of the header.
An alternative would be to add each object being transmitted to a container and then serialize/transmit/deserialize the container and then deserialize each object in the container.
|
|
|
|
|