I'm trying to use the below code to show a Balloon notification. I've verified that it's being executed by using breakpoints. It's also showing no errors.
What should I do to debug this since it's not throwing errors and not showing the balloon?
private void showBalloon(string title, string body)
{
NotifyIcon notifyIcon = new NotifyIcon();
notifyIcon.Visible = true;
if (title != null)
{
notifyIcon.BalloonTipTitle = title;
}
if (body != null)
{
notifyIcon.BalloonTipText = body;
}
notifyIcon.ShowBalloonTip(30000);
}
You have not actually specified an icon to display in the task bar. Running your code in LINQPad, by simply adding notifyIcon.Icon = SystemIcons.Application before the call to ShowBalloonTip I was able to get the tip to be displayed. Also note that you should call Dispose when you are done with your NotifyIcon instance.
Matthew identified the issue, but I still struggled to put all the pieces together. So I thought a concise example that works in LINQPad as-is would be helpful (and presumably elsewhere). Just reference the System.Windows.Forms assembly, and paste this code in.
var notification = new System.Windows.Forms.NotifyIcon()
{
Visible = true,
Icon = System.Drawing.SystemIcons.Information,
// optional - BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info,
// optional - BalloonTipTitle = "My Title",
BalloonTipText = "My long description...",
};
// Display for 5 seconds.
notification.ShowBalloonTip(5000);
// This will let the balloon close after it's 5 second timeout
// for demonstration purposes. Comment this out to see what happens
// when dispose is called while a balloon is still visible.
Thread.Sleep(10000);
// The notification should be disposed when you don't need it anymore,
// but doing so will immediately close the balloon if it's visible.
notification.Dispose();
See the below source code.
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace ShowToolTip
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btBallonToolTip_Click(object sender, EventArgs e)
{
ShowBalloonTip();
this.Hide();
}
private void ShowBalloonTip()
{
Container bpcomponents = new Container();
ContextMenu contextMenu1 = new ContextMenu();
MenuItem runMenu = new MenuItem();
runMenu.Index = 1;
runMenu.Text = "Run...";
runMenu.Click += new EventHandler(runMenu_Click);
MenuItem breakMenu = new MenuItem();
breakMenu.Index = 2;
breakMenu.Text = "-------------";
MenuItem exitMenu = new MenuItem();
exitMenu.Index = 3;
exitMenu.Text = "E&xit";
exitMenu.Click += new EventHandler(exitMenu_Click);
// Initialize contextMenu1
contextMenu1.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] { runMenu, breakMenu, exitMenu });
// Initialize menuItem1
this.ClientSize = new System.Drawing.Size(0, 0);
this.Text = "Ballon Tootip Example";
// Create the NotifyIcon.
NotifyIcon notifyIcon = new NotifyIcon(bpcomponents);
// The Icon property sets the icon that will appear
// in the systray for this application.
string iconPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\setup-icon.ico";
notifyIcon.Icon = new Icon(iconPath);
// The ContextMenu property sets the menu that will
// appear when the systray icon is right clicked.
notifyIcon.ContextMenu = contextMenu1;
notifyIcon.Visible = true;
// The Text property sets the text that will be displayed,
// in a tooltip, when the mouse hovers over the systray icon.
notifyIcon.Text = "Morgan Tech Space BallonTip Running...";
notifyIcon.BalloonTipText = "Morgan Tech Space BallonTip Running...";
notifyIcon.BalloonTipTitle = "Morgan Tech Space";
notifyIcon.ShowBalloonTip(1000);
}
void exitMenu_Click(object sender, EventArgs e)
{
this.Close();
}
void runMenu_Click(object sender, EventArgs e)
{
MessageBox.Show("BallonTip is Running....");
}
}
}
For the sake of future coders:
the [timeout] parameter is deprecated as of windows vista
See: C# NotifyIcon Show Balloon Parameter Deprecated
So you might as well just put 0 into the parameter for > Windows Vista. What's worse, comments on the linked answer suggests that the replacement for these balloons, toast notifications, were only introduced in Windows 8. So for poor old Windows 7 falling between two stools, with Vista < 7 < 8, we seem to be at the mercy of however long Windows wants to keep that balloon there! It does eventually fade away, I've noticed, but after some empirical testing I'm quite sure that parameter is indeed being ignored.
So, building on the answers above, and in particular taking the lambda functions suggested by #jlmt in the comments, here's a solution that works for me on Windows 7:
//Todo: use abstract factory pattern to detect Windows 8 and in that case use a toastnotification instead
private void DisplayNotificationBalloon(string header, string message)
{
NotifyIcon notifyIcon = new NotifyIcon
{
Visible = true,
Icon = SystemIcons.Application
};
if (header != null)
{
notifyIcon.BalloonTipTitle = header;
}
if (message != null)
{
notifyIcon.BalloonTipText = message;
}
notifyIcon.BalloonTipClosed += (sender, args) => dispose(notifyIcon);
notifyIcon.BalloonTipClicked += (sender, args) => dispose(notifyIcon);
notifyIcon.ShowBalloonTip(0);
}
private void dispose(NotifyIcon notifyIcon)
{
notifyIcon.Dispose();
}
Notes
I've put a TODO in there to write another implementation for Windows
8, as people are 50/50 now on Windows 7/8 so would be good to support
a newer functionality. I guess anyone else coding this for multiple
versions of windows should probably do the same, ideally. Or just
stop supporting 7 and switch to using ToastNotification.
I purposely defined the disposal in a function so I could debug and verify that the breakpoint was indeed being hit.
ShowBalloonnTip takes the number of milliseconds. 3 milliseconds might be too fast for you to even see. Try something more like 3000
You might need to pass a component model to the contructor. It's what I see in all the examples. Sorry been a long time since I've used it. See first answer here:
NotifyIcon not showing
Take a look at the example here http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx
I see some distinct differences between it an your code, there are many pieces you're leaving out such as creating a ComponentModelContainer and passing that into the NotifyIcon's constructor.
Related
I'm starting with SAP B1 UI API (9.0) and I'm trying to handle a button click without any luck so far. This is how I'm doing it (removing unnecessary to make it shorter):
static void Main(string[] args)
{
SetApplication(args);
var cParams = (FormCreationParams)App.CreateObject(BoCreatableObjectType.cot_FormCreationParams);
cParams.UniqueID = "MainForm_";
cParams.BorderStyle = BoFormBorderStyle.fbs_Sizable;
_form = App.Forms.AddEx(cParams);
/*Setting form's title, left, top, width and height*/
// Button
var item = _form.Items.Add("BtnClickMe", BoFormItemTypes.it_BUTTON);
/*Setting button's left, top, width and height*/
var btn = (Button)item.Specific;
btn.Caption = "Click Me";
_form.VisibleEx = true;
App.ItemEvent += new _IApplicationEvents_ItemEventEventHandler(App_ItemEvent);
}
private static void SetApplication(string[] args)
{
string connectionString = args[0];
int appId = -1;
try
{
var guiApi = new SboGuiApi();
guiApi.Connect(connectionString);
App = guiApi.GetApplication(appId);
}
catch (Exception e)
{ /*Notify error and exit*/ }
}
private static void App_ItemEvent(string FormUID, ref ItemEvent pVal, out bool BubbleEvent)
{
BubbleEvent = true;
if (FormUID == "MainForm_" && pVal.EventType == BoEventTypes.et_CLICK &&
pVal.BeforeAction && pVal.ItemUID == "BtnClickMe")
{
App.MessageBox("You just click on me!");
}
}
When I click the button nothing happens, is this the way to go? I've made so many variations in the handler method but nothing yet. Another detail is that the visual studio's debugger terminates as soon as the addon is started (maybe this has something to do with my problem).
I hope you can help me. Thanks in advance.
David.
Since the application stops running there are two possible answers to this question depending on what you prefer to use.
If you are using the SAPbouiCOM library you need a way to keep the application running, the way I use is the System.Windows.Forms.Application.Run(); from the windows forms assembly.
If you are using the SAPBusinessOneSDK and SAPbouiCOM.Framework as a reference you can use the App.Run();.
Both of these need to be invoked as soon as your setup code has run.
I still have a problem with the splash screen. I don't want to use the property SC.TopMost=true.
Now my application scenario is as follows:
in progeram.cs:
[STAThread]
static void Main()
{
new SplashScreen(_tempAL);// where _tempAL is an arrayList
Application.Run(new Form1(_tempAL));
}
in SplashScreen class:
public SplashScreen(ArrayList _Data)
{
DisplaySplash()
}
private void DisplaySplash()
{
this.Show();
this.TopMost = true;
this.CenterToScreen();
this.SetTopLevel(true);
_allServerNarrators = new string[10];
for (int i = 0; i < _allServerNarrators.Length; i++)
_allServerNarrators[i] = null;
GetFromServer();
this.Hide();
_serverData = new ArrayList();
_thisData.Add(_allServerNarrators);
_thisData.Add(_serverNarrators);
}
private void GetFromServer()
{
_serverNarrators = new ArrayList();
string _file = "Suras.serverNar";
if (!Directory.Exists("c:\\ASGAQuraan"))
Directory.CreateDirectory("c:\\ASGAQuraan");
while (counter < 4 && _serverFiles == null)
{
if (Download("c:\\ASGAQuraan", _ftpServerIP, _file))
{
StreamReader _strReader = new StreamReader
("c:\\ASGAQuraan\\"+_file,System.Text.Encoding.Default);
string _line = _strReader.ReadLine();
string _word;
while (true)
{
while (_line != null)
{
_word = _line.Substring(0, _line.IndexOf("*"));
int _narId = Convert.ToInt32(_word);
_line = _line.Substring(2);
int k = 0;
_serverNarratorNode = new ArrayList();
while (true)
{
int ind = _line.IndexOf("*");
if (ind > 0 && ind < _line.Length)
{
string str = _line.Substring(0, (ind));
if (k == 0)
{
_allServerNarrators[_narId] = str;
_serverNarratorNode.Add(str);
}
else
{
_serverNarratorNode.Add(str);
}
_line = _line.Substring(ind + 1);
k++;
}
else
{
_line = null;
break;
}
}
_serverNarrators.Add(_serverNarratorNode);
_serverFiles = "added";
}
_line = _strReader.ReadLine();
if (_line == null)
{
break;
}
}
}
else
counter++;
}
}
What I want is something in the splash screen class which waits until the thread finishes.
For more details, please tell me what I need to tell you.
Same question, same answer:
The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WindowsFormsApplication1 {
static class Program {
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new MyApp().Run(args);
}
}
class MyApp : WindowsFormsApplicationBase {
protected override void OnCreateSplashScreen() {
this.SplashScreen = new frmSplash();
}
protected override void OnCreateMainForm() {
// Do your time consuming stuff here...
//...
System.Threading.Thread.Sleep(3000);
// Then create the main form, the splash screen will close automatically
this.MainForm = new Form1();
}
}
}
You've entered dangerous territory by creating UI prior to your call to Application.Run(). Application.Run is essentially your program's message pump. By displaying the UI before you start the application's message pump, you make typical UI interaction effectively impossible on the premature UI. For a splash screen this may not seem relevant, but it will matter if (e.g.) there's a request to make the splash screen disappear if it's clicked on, or you want to use a BackgroundWorker.
These can be worked around by creating a message pump in your splash screen (by making it modal via a call to ShowDialog() instead of Show()), but that's treating the symptom when treating the problem really isn't that difficult.
I'd strongly encourage nobugz's answer in this case. The framework provides the support you need. While features in the Microsoft.VisualBasic namespace aren't always very discoverable to C# programmers, they can be a real timesaver and lifesaver for cases like this.
Good luck!
Following across 2 threads is a bit confusing, but I'm going to take a stab and say this...
I don't fully understand your design here, but if the issue is that when you launch a second application the splash screen form turns white... It's most likely due to the fact that splash screen is busy executing all of that code in GetFromServer(). So busy that it has no time to re-paint itself.
To remedy this problem I would suggest that you use the BackGroundWorker component to execute the GetFromServer method. This will run that method in a separate thread and leave the form's thread free to re-paint itself.
Unfortunately I don't have enough reputation to comment on someones answer yet. :( This is meant to be the answer to Colonel Panics comment on Hans Passants answer.
His problem was that a MessageBox shown from new FormMain(args)will be shown behind the splash screen. The key is to invoke the MessageBox from the thread the splash screen runs in:
splashScreen.Invoke(new Action(() => {
MessageBox.Show(splashScreen, "the message");
}));
Where splashScreen is a reference to the splash screen object that has been created in OnCreateSplashScreen and obviously has to be given to the new Form1 object.
You really should give more details about your problem. I could be completely wrong, but I'm going to take a shot in the dark. From what I'm imagining is going on and you want, you want the splash screen to show, do some processing in another thread, then the splash screen to go away when finished.
To do this, you're going to want to move the GetFromServer() call to a BackgroundWorker. Then move the
this.Hide();
_serverData = new ArrayList();
_thisData.Add(_allServerNarrators);
_thisData.Add(_serverNarrators);
code to the BackgroundWorker_RunWorkerCompleted event handler.
To use the BackgroundWorker:
1) Initialize the BackGroundWorker
BackgroundWorker myWorker = new BackgroundWorker();
2) Add event handlers
myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork);
//put the work you want done in this one
myWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted);
//this gets fired when the work is finished
3) Add code to the event handlers.
4) Call myWorker.RunWorkerAsync() to start working.
As a separate note, you don't seem to be doing anything with the ArrayList that you're passing to the splash screen's constructor. Is this intended?
I have this one problem that I can't get over. I think it will be something really simple but I just was not able to find out.. I am trying to open new window here for editing contact when user double click on one row in listview. Window normally opens but the problem is it won't open in front of current main window but behind it so it is not visible and can easily confuse user. I have tried few methods like BringIntoView() or playing with focus but nothing helped.
Please help me with this. Thanks!
Code:
void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
editContact();
}
private void editContact()
{
Window1 win = new Window1("edit");
DatabaseHandler handler = new DatabaseHandler();
win.Show();
List<Contact> listie = handler.GetContactList();
var selected = listview_contacts.SelectedItem as Contact;
win.textbox_id.Text = selected.cId.ToString();
win.textbox_name.Text = selected.Name.ToString();
win.textbox_address.Text = selected.Address.ToString();
win.textbox_email.Text = selected.Email.ToString();
win.textbox_name.Focus();
win.textbox_name.SelectionStart = win.textbox_name.Text.Length;
}
private void editContact()
{
using(Window1 win = new Window1("edit"))
{
DatabaseHandler handler = new DatabaseHandler();
List<Contact> listie = handler.GetContactList();
var selected = listview_contacts.SelectedItem as Contact;
win.textbox_id.Text = selected.cId.ToString();
win.textbox_name.Text = selected.Name.ToString();
win.textbox_address.Text = selected.Address.ToString();
win.textbox_email.Text = selected.Email.ToString();
win.textbox_name.Focus();
win.textbox_name.SelectionStart = win.textbox_name.Text.Length;
win.ShowDialog();
// do something with whatever win1 did.
// if its say OK Cancrl form
// if (win.ShowDialog() == DialogResult.OK) { // do something }
}
}
Will probably fix your issue. However without seeing the rest of your code, or knowing your intent, I can't tell you exactly how badly you've gone wrong.
For example at least all the code setting up win.textbox, should be in win...
Try
win.ShowDialog();
Which should open the new windows as a modal window.
You could try
win.Show(this);
This will enable the user to interact with the main form when your editing dialog opens.
Or you can try
win.ShowDialog();
This will block the main form when your editing dialog opens.
I have a C# program that sits in the system tray and pops up a notification balloon now and then. I'd like to provide 2-3 buttons on the notification balloon to allow the user to take various actions when the notification appears - rather than, for example, having to click the notification balloon to display a form containing buttons for each possible action.
I'm looking for suggestions on the best way to go about implementing this.
Edit: clarification, I want to provide buttons on the notification balloon so the user can take direct action on the notification rather than having to take action through some other part of the application (a form or menu for example).
There's no built-in method for this. I would suggest writing your own "balloon" and activating that instead of calling .ShowBalloon()
This is how I do it. It may not be the correct way of doing it. I do this way because .ShowBalloonTip(i) doesn't work as expected for me. It doesn't stay for i seconds and go off. So I do in another thread and forcefully dispose off.
private static NotifyIcon _notifyIcon;
//you can call this public function
internal static void ShowBalloonTip(Icon icon)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync(icon);
}
private static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Show(e);
Thread.Sleep(2000); //meaning it displays for 2 seconds
DisposeOff();
}
private static void Show(DoWorkEventArgs e)
{
_notifyIcon = new NotifyIcon();
_notifyIcon.Icon = (Icon)e.Argument;
_notifyIcon.BalloonTipTitle = "Environment file is opened";
_notifyIcon.BalloonTipText = "Press alt+tab to switch between environment files";
_notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
_notifyIcon.Visible = true;
_notifyIcon.ShowBalloonTip(2000); //sadly doesnt work for me :(
}
private static void DisposeOff()
{
if (_notifyIcon == null)
return;
_notifyIcon.Dispose();
_notifyIcon = null;
}
I still have a problem with the splash screen. I don't want to use the property SC.TopMost=true.
Now my application scenario is as follows:
in progeram.cs:
[STAThread]
static void Main()
{
new SplashScreen(_tempAL);// where _tempAL is an arrayList
Application.Run(new Form1(_tempAL));
}
in SplashScreen class:
public SplashScreen(ArrayList _Data)
{
DisplaySplash()
}
private void DisplaySplash()
{
this.Show();
this.TopMost = true;
this.CenterToScreen();
this.SetTopLevel(true);
_allServerNarrators = new string[10];
for (int i = 0; i < _allServerNarrators.Length; i++)
_allServerNarrators[i] = null;
GetFromServer();
this.Hide();
_serverData = new ArrayList();
_thisData.Add(_allServerNarrators);
_thisData.Add(_serverNarrators);
}
private void GetFromServer()
{
_serverNarrators = new ArrayList();
string _file = "Suras.serverNar";
if (!Directory.Exists("c:\\ASGAQuraan"))
Directory.CreateDirectory("c:\\ASGAQuraan");
while (counter < 4 && _serverFiles == null)
{
if (Download("c:\\ASGAQuraan", _ftpServerIP, _file))
{
StreamReader _strReader = new StreamReader
("c:\\ASGAQuraan\\"+_file,System.Text.Encoding.Default);
string _line = _strReader.ReadLine();
string _word;
while (true)
{
while (_line != null)
{
_word = _line.Substring(0, _line.IndexOf("*"));
int _narId = Convert.ToInt32(_word);
_line = _line.Substring(2);
int k = 0;
_serverNarratorNode = new ArrayList();
while (true)
{
int ind = _line.IndexOf("*");
if (ind > 0 && ind < _line.Length)
{
string str = _line.Substring(0, (ind));
if (k == 0)
{
_allServerNarrators[_narId] = str;
_serverNarratorNode.Add(str);
}
else
{
_serverNarratorNode.Add(str);
}
_line = _line.Substring(ind + 1);
k++;
}
else
{
_line = null;
break;
}
}
_serverNarrators.Add(_serverNarratorNode);
_serverFiles = "added";
}
_line = _strReader.ReadLine();
if (_line == null)
{
break;
}
}
}
else
counter++;
}
}
What I want is something in the splash screen class which waits until the thread finishes.
For more details, please tell me what I need to tell you.
Same question, same answer:
The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WindowsFormsApplication1 {
static class Program {
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new MyApp().Run(args);
}
}
class MyApp : WindowsFormsApplicationBase {
protected override void OnCreateSplashScreen() {
this.SplashScreen = new frmSplash();
}
protected override void OnCreateMainForm() {
// Do your time consuming stuff here...
//...
System.Threading.Thread.Sleep(3000);
// Then create the main form, the splash screen will close automatically
this.MainForm = new Form1();
}
}
}
You've entered dangerous territory by creating UI prior to your call to Application.Run(). Application.Run is essentially your program's message pump. By displaying the UI before you start the application's message pump, you make typical UI interaction effectively impossible on the premature UI. For a splash screen this may not seem relevant, but it will matter if (e.g.) there's a request to make the splash screen disappear if it's clicked on, or you want to use a BackgroundWorker.
These can be worked around by creating a message pump in your splash screen (by making it modal via a call to ShowDialog() instead of Show()), but that's treating the symptom when treating the problem really isn't that difficult.
I'd strongly encourage nobugz's answer in this case. The framework provides the support you need. While features in the Microsoft.VisualBasic namespace aren't always very discoverable to C# programmers, they can be a real timesaver and lifesaver for cases like this.
Good luck!
Following across 2 threads is a bit confusing, but I'm going to take a stab and say this...
I don't fully understand your design here, but if the issue is that when you launch a second application the splash screen form turns white... It's most likely due to the fact that splash screen is busy executing all of that code in GetFromServer(). So busy that it has no time to re-paint itself.
To remedy this problem I would suggest that you use the BackGroundWorker component to execute the GetFromServer method. This will run that method in a separate thread and leave the form's thread free to re-paint itself.
Unfortunately I don't have enough reputation to comment on someones answer yet. :( This is meant to be the answer to Colonel Panics comment on Hans Passants answer.
His problem was that a MessageBox shown from new FormMain(args)will be shown behind the splash screen. The key is to invoke the MessageBox from the thread the splash screen runs in:
splashScreen.Invoke(new Action(() => {
MessageBox.Show(splashScreen, "the message");
}));
Where splashScreen is a reference to the splash screen object that has been created in OnCreateSplashScreen and obviously has to be given to the new Form1 object.
You really should give more details about your problem. I could be completely wrong, but I'm going to take a shot in the dark. From what I'm imagining is going on and you want, you want the splash screen to show, do some processing in another thread, then the splash screen to go away when finished.
To do this, you're going to want to move the GetFromServer() call to a BackgroundWorker. Then move the
this.Hide();
_serverData = new ArrayList();
_thisData.Add(_allServerNarrators);
_thisData.Add(_serverNarrators);
code to the BackgroundWorker_RunWorkerCompleted event handler.
To use the BackgroundWorker:
1) Initialize the BackGroundWorker
BackgroundWorker myWorker = new BackgroundWorker();
2) Add event handlers
myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork);
//put the work you want done in this one
myWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted);
//this gets fired when the work is finished
3) Add code to the event handlers.
4) Call myWorker.RunWorkerAsync() to start working.
As a separate note, you don't seem to be doing anything with the ArrayList that you're passing to the splash screen's constructor. Is this intended?