Showing Form from a thread not rendering perfectly - c#

I am developing a chat application using jabber-net opensource library..
my aim is to display a form (chat window ) when a message is coming.
But when I use this code, Form appears in the task bar,,, not perfectly rendered...
seems like this... More over I can see the form only when I mousehover the Icon on taskbar (Hail Windows 7)... Any form are like this...
Click here for Output Image
my code is this...
public jabber.client.JabberClient jabberClient1;
jabberClient1.User = UserName;
jabberClient1.Password = Password;
jabberClient1.Resource = resource;
jabberClient1.AutoRoster = true;
jabberClient1.OnMessage += new MessageHandler(jabberClient1_OnMessage);
private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
{
try
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}

you have to use chw.ShowDialog()
or use if invokerequired
private delegate void dlgInvokeRequired();
public void InvokeMethode()
{
if (this.InvokeRequired == true)
{
dlgInvokeRequired d = new dlgInvokeRequired(InvokeMethode);
this.Invoke(d);
} else
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}

I have solved it myself...
I have to use
JabberClient1.InvokeControl = FormInstance;
and, the FormInstance should be shown Before the chat window appears....
ie, It can be the contact window (Roster)....

Related

How to prevent hanging of application when a button is clicked multiple times?

I have an application where user can click on a Scan button to scan the image to preview in the application. When user clicks, usually a "Preparing to scan" message will be shown and goes away when the scan is 100% complete.
The scan works fine. The problem if I stress test it by pressing the scan button many times while it's doing it's work, the application completely hangs and the message just stays there and I had to restart my whole application.
The code: It's just a small section
private void ScanStripButton_Click(object sender, EventArgs e)
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
Any idea on how to prevent this issue?
Appreciate the help
EDIT:
public void StartTwainScan()
{
Boolean EnableUI = false;
Boolean ADF = false;
Boolean EnableDuplex = false;
if (Properties.Settings.Default.TwainShow.Equals("1"))
{
EnableUI = true;
}
if (Properties.Settings.Default.ScanType.Equals("2"))
{
ADF = true;
}
if (Properties.Settings.Default.DuplexEnable.Equals("1"))
{
EnableDuplex = true;
}
var rs = new ResolutionSettings
{
Dpi = GetResolution(),
ColourSetting = GetColorType()
};
var pg = new PageSettings()
{
Size = GetPageSize()
};
var settings = new ScanSettings
{
UseDocumentFeeder = ADF,
ShowTwainUI = EnableUI,
ShowProgressIndicatorUI = true,
UseDuplex = EnableDuplex,
Resolution = rs,
Page = pg
};
try
{
TwainHandler.StartScanning(settings);
}
catch (TwainException ex)
{
MessageBox.Show(ex.Message);
//Enabled = true;
//BringToFront();
}
}
This isn't going to be the correct answer, but you haven't shown enough code to give you the right code. It should point you in the right direction.
private void ScanStripButton_Click(object sender, EventArgs e)
{
ScanStripButton.Enabled = false;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
ScanStripButton.Enabled = true;
}
Basically you disable the button when the scan starts and enable it when it finishes.
private async void ScanStripButton_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
});
}
or
private bool clicked = false;
private void ScanStripButton_Click(object sender, EventArgs e)
{
try
{
if(clicked)
return;
clicked = true;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
finally
{
clicked = false;
}
}

Is there any way to add RichTextBox to C# Xamarin project for Android?

I have a problem translating a C# project that I created for Windows, to Android Xamarin. I have searched the web to find any solution about RichTextBox and other functions and components that I used for building the Windows version program but I couldn't find any good solution except one topic here but it didn't help me.
If there is no way to add something like a richtextbox, is there any other textbox that supports .Lines so I can get the correct line number?
Here is a part of my code:
private void ThreadTask1()
{
string link = "http://example.com/music-today.php";
int TimeToWait = 300;
int check_ID = 0;
string ParsedResult = null;
HtmlAgilityPack.HtmlDocument doc = null;
HtmlWeb web1 = new HtmlWeb();
while (true) {
ParsedResult = "";
RichTextBox1.Clear();
RichTextBox2.Clear();
web1.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)";
web1.UsingCache = false;
web1.UseCookies = true;
doc = web1.Load(link);
HtmlNode div = doc.DocumentNode.SelectSingleNode("//div[#class='latest-song14']");
if ((div != null)) {
ParsedResult = div.InnerText.Trim();
RichTextBox1.Text = ParsedResult;
RichTextBox2.Text = RichTextBox1.Lines[0];
if (!RichTextBox2.Text.Contains("dj")) {
Sound vol = new Sound("nircmdc.exe");
vol.setVol(40);
while (true) {
MyMusicInformer.My.MyProject.Computer.Audio.Play("C:\\Windows\\media\\Alarm01.wav", AudioPlayMode.Background);
System.Threading.Thread.Sleep(700);
MyMusicInformer.My.MyProject.Computer.Audio.Play("C:\\Windows\\media\\Alarm01.wav", AudioPlayMode.Background);
System.Threading.Thread.Sleep(700);
MyMusicInformer.My.MyProject.Computer.Audio.Play("C:\\Windows\\media\\Alarm01.wav", AudioPlayMode.Background);
System.Threading.Thread.Sleep(5000);
}
} else {
check_ID = check_ID + 1;
RichTextBox2.Text = "No new song yet. Try (" + check_ID.ToString() + ")";
}
}
System.Threading.Thread.Sleep(TimeToWait * 1000);
}
}
private Thread trd1;
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
trd1 = new Thread(ThreadTask1);
trd1.IsBackground = true;
trd1.Start();
}
I only want to be able to be informed when there is a new song update. In Visual Studio I can only see the "Multiline Text" option but it can't solve my problem.
Thanks for your time.
Have you tried Xamarin.Forms.Editor control? I'm sure that it can help you.

How to create a window on Internet Explorer

I try to create a window on Internet Explorer,just like this:
I wrote this with C++
But I do not know how to design a dialog with MFC,I want to develop this program with c#.
I already know that using BHO can do this work.Here is the core code:
public int SetSite(object site)
{
if (site != null)
{
webBrowser = (SHDocVw.WebBrowser)site;
webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
}
else
{
webBrowser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
webBrowser = null;
}
return 0;
}
onDocumentComplete :
SHDocVw.WebBrowser webBrowser;
public void OnDocumentComplete(object pDisp, ref object URL)
{
Form form1 = new Form();
IntPtr p = new IntPtr(webBrowser.HWND);
Control con = Control.FromHandle(p);
con.Controls.Add(form1);
}
But this do not work.Please tell me waht's wrong with my code and how can I do this work.Thank you.

How to implement a userdefined cursor in C#?

I want to define my own Cursor as the Current Cursor in my WPF Application, but wenn I try to create a new Cursor Object from my .cur File, I get an Error.
My Code is
private void NewFile()
{ ...
iEvent_dragdrop = (HTMLDocumentEvents2_Event)doc;
iEvent_dragdrop.ondragstart += new HTMLDocumentEvents2_ondragstartEventHandler(IEvent_ondragstart);
}
private bool IEvent_ondragstart(IHTMLEventObj pEvtObj)
{
x_start = pEvtObj.x; // Read position of Mouse
y_start = pEvtObj.y;
....
if (File.Exists("MyCursor.cur"))
{
System.Windows.Forms.Cursor myCursor = new System.Windows.Forms.Cursor(GetType(), "MyCursor.cur");
System.Windows.Forms.Cursor.Current = myCursor;
//System.Windows.Forms.MessageBox.Show("File exist");
}
else System.Windows.Forms.MessageBox.Show("File does not exist");
return false;
}
When I try to drag the HTML Object, I get the error System.NullReferenceException wasn´t handled in the source-code. But I tested if the File exists ....
Can anyone tell me, what´s my mistake?
Thanks!
I recommend searching the web before asking. First search result for the title explains everything you should need to know.
Try this out:
class Program {
[System.STAThread]
static void Main(string[] args) {
byte[] cursorBytes = new System.Net.WebClient().DownloadData(#"https://github.com/tlorach/nvGraphy/raw/master/cursor1.cur");
System.IO.Stream cursorStream = new System.IO.MemoryStream(cursorBytes, false);
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(cursorStream);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
}
}
Or this:
class Program {
[System.STAThread]
static void Main(string[] args) {
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Filter = "Cursor (*.cur)|*.cur";
switch(openDialog.ShowDialog()) {
case System.Windows.Forms.DialogResult.OK:
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(openDialog.FileName);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
break;
}
}
}

Open Windows Form with opcv From wpf windows

note I am new in Wpf >
I have project that decode qr code by using opencv library throw web cam >
and it running successfully
now I wanna to using this project in new Wpf project >
after adding new wpf project and make reference to WinForms application >
and this my simple code to open WinForm >
public void runnow(){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CameraCapture.cameraCapture()); }
by ruining give me this exception >
The type initializer for 'Emgu.CV.CvInvoke' threw an exception.>
what can I do for solve this
C# code
public partial class CameraCapture : Form
{
Capture capture;
bool Capturing;
Bitmap bimap;
private Reader reader;
private Hashtable hint;
libAES libEncryption = new libAES();
string Mykey = "";
public static String dataDecrypted="";
public CameraCapture()
{
InitializeComponent();
}
private void Mains(object sender, EventArgs arg) // Start function main to encode Qr code
{
Image<Bgr, Byte> image = capture.QueryFrame();
if (image != null)
{
bimap = image.ToBitmap();
pictureBox1.Image = bimap;
reader = new QRCodeReader();
hint = new Hashtable(); // Add some elements to the hash table. There are no duplicate keys, but some of the values are duplicates.
hint.Add(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
RGBLuminanceSource source = new RGBLuminanceSource(bimap, bimap.Width, bimap.Height); //This class is used to help decode images from files which arrive as RGB data from* Android bitmaps. It does not support cropping or rotation.
BinaryBitmap img = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Result result = null;
try
{
result = reader.decode(img, hint);
dataDecrypted = libEncryption.Decrypt(result.Text, Mykey);
}
catch
{
dataDecrypted = "";
}
if (result == null)
{
label1.Text = " no decode";
}
else
{
label4.Text = result.Text;
label1.Text = dataDecrypted;
capture.Dispose();
}
}
} // end function Main
private void btnStart_Click(object sender, EventArgs e)
{
if (capture == null)
{
try
{
capture = new Capture(); // **the exption thown here**
}
catch (NullReferenceException exception)
{
MessageBox.Show(exception.Message);
}
}
if (capture != null)
{
if (Capturing)
{
btnStart.Text = "Start Capture";
Application.Idle -= Mains;
}
else
{
btnStart.Text = "Stop Capture";
Application.Idle += Mains;
}
Capturing = !Capturing;
}
}
private void Release()
{
if (capture != null)
capture.Dispose();
}}
If you want to host WinForm in WPF, you need to use host control System.Windows.Forms.Integration.WindowsFormsHost
WPF provides many controls with a rich feature set. However, you may
sometimes want to use Windows Forms controls on your WPF pages. For
example, you may have a substantial investment in existing Windows
Forms controls, or you may have a Windows Forms control that provides
unique functionality.
Example code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
// Create the MaskedTextBox control.
MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");
// Assign the MaskedTextBox control as the host control's child.
host.Child = mtbDate;
// Add the interop host control to the Grid
// control's collection of child controls.
this.grid1.Children.Add(host);
}
Check =>
http://msdn.microsoft.com/en-us/library/ms751761.aspx

Categories

Resources