|
You've declared and created the timer in a method; I'd assume it gets disposed as soon as it exits the method. Try something like below;
public partial class App : Application
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
It's a little bit confusing now ... I found one mistake :-|
The App.xaml is defined this way:
<Application x:Class="Technewlogic.Samples.WpfModalDialog.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
<Application.Resources>
</Application.Resources>
</Application>
So I had to correct the fiering of the timer in the App.xaml.cs this way:
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Windows;
namespace Technewlogic.Samples.WpfModalDialog
{
public partial class App : Application
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
TopMost = true;
this.TopMost = true;
InitializeComponent();
}
public bool TopMost { get; set; }
[SuppressUnmanagedCodeSecurity]
public class SafeNativeMethods
{
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 SetForegroundWindow(int hWnd);
}
private void triMain_Click(object sender, System.EventArgs e)
{
int hWnd = SafeNativeMethods.FindWindow(null, "Test");
SafeNativeMethods.SetForegroundWindow(hWnd);
TopMost = true;
}
private void Application_Startup(object sender, StartupEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
bool createdNew;
Mutex mutex = new Mutex(true, this.GetType().GUID.ToString(), out createdNew);
if (createdNew)
{
Window window = new MainWindow();
window.Closed += (sender2, args) => mutex.Close(); ;
window.Show();
}
else
{
mutex.Close();
Application.Current.Shutdown();
}
}
}
}
I've tested the timer with a MessageBox => worked
But how is it possible to renew the TopMost for the MainWindow (Mainwindow.xaml.cs) or for the App?
Should I use the TopMost-Function better in the MainWindow-Element?
And I have a nother question:
This makes a CA1401:
public class SafeNativeMethods
{
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 SetForegroundWindow(int hWnd);
}
How can I correct this?
|
|
|
|
|
My corrections didn't work ...
So I will now try this way:
Now my MainWindow.xaml.cs is coded this way:
using System;
using System.Diagnostics;
using System.Windows;
using System.Runtime.InteropServices;
namespace Technewlogic.Samples.WpfModalDialog
{
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
const int swRestore = 9;
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
var me = Process.GetCurrentProcess();
var arrProcesses = Process.GetProcessesByName(me.ProcessName);
if (arrProcesses.Length > 1)
{
for (var i = 0; i < arrProcesses.Length; i++)
{
if (arrProcesses[i].Id != me.Id && arrProcesses[i].SessionId == me.SessionId)
{
IntPtr hWnd = arrProcesses[i].MainWindowHandle;
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, swRestore);
}
SetForegroundWindow(hWnd);
break;
}
}
}
}
public MainWindow()
{
Window w = new Window();
w.Top = -100;
w.Left = -100;
w.Width = 1;
w.Height = 1;
w.WindowStyle = WindowStyle.ToolWindow;
w.Show();
this.Owner = w;
w.Hide();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
InitializeComponent();
ModalDialog.SetParent(ModalDialogParent);
}
private void ShowModalDialog_Click(object sender, RoutedEventArgs e)
{
var res = ModalDialog.ShowHandlerDialog(MessageTextBox.Text);
var resultMessagePrefix = "Result: ";
if (res)
ResultText.Text = resultMessagePrefix + "OK";
else
ResultText.Text = resultMessagePrefix + "Break";
}
}
}
|
|
|
|
|
What does "didn't work" mean? Did it throw an exception? Failed silently? Did the timer fail, or getting to topmost?
The previous link from SO is the only real supported scenario; I'd recommend focussing on that.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Sorry for giving not enough informations about the fail
=> getting topmost failed
There is no exception and the timer is working without errors...
|
|
|
|
|
If you open a normal Window, it shows in front of your window?
Does the same happen without timer?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Yes, it is shown in front of a normal window.
I think the other problem ist that I'm using UserControl in WPF.
Because of this the handle will always be 0 ...
Is there a way to set/create/place a handle in my WPF including UserControl?
The Console-Outputs I created always say this:
********************** Timer_Tick-Anfang **********************
Setze ShowWindowAsync für den System.Diagnostics.Process (Test)-Handle 0 mit dem SW_RESTORE-Parameter 9
Setze ForegroundWindow für System.Diagnostics.Process (Test) mit dem Handle 0
Setze TOPMOST für Prozess System.Diagnostics.Process (Test) mit dem Handle 0
Setze TOP für Prozess System.Diagnostics.Process (Test) mit dem Handle 0
hWnd: 0
********************** Timer_Tick-Ende ************************
I am loading the UserControl in the main window this way:
InitializeComponent();
ModalDialog.SetParent(ModalDialogParent);
|
|
|
|
|
Benjamin.Buhr wrote: I think the other problem ist that I'm using UserControl in WPF. A UserControl is not a Window, and cannot be topmost; it needs to be hosted in a Window.
Then again, it would not be very friendly to have a usercontrol modify its parents' behaviour.
In WinForms (I don't do WPF) there's an event that is fired on the form as soon as the handle is created; it is fired quickly after the constructor. That's where you could initialize your UC.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
hi,
i have Windows-Mobile program that work with weight Connecting through rs232.
its work excellent - If the program works in a period of time, it starts to slow
down and even get stuck at some point.
my code:
Hide Expand Copy Code
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recepcion);
private SerialPort port;
StringBuilder SB;
private void Recepcion(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SB = new StringBuilder(1000);
Application.DoEvents();
System.Threading.Thread.Sleep(122);
SB.Append(port.ReadExisting());
port.DiscardInBuffer();
this.Invoke(new EventHandler(Actualizar));
}
catch { }
}
string MOMO1, MOMO2;
string[] WI;
string ALL;
private void Actualizar(object s, EventArgs e)
{
ALL = SB.ToString().Trim();
WI = ALL.Split(',');
ALL = WI[2].ToString().Trim();
MOMO1 = ALL.Replace("+", "").Replace("g", "").Replace("ST", "").Replace("GS", "").Replace("US", "");
if (MOMO1 != "")
{
MOMO2 = MOMO1;
}
lblMSG.Font = new Font("Ariel", 48, FontStyle.Bold);
lblMSG.Text = MOMO2;
Check_Weight();
GC.Collect();
}
Can anyone advise me why and how to solve it ?
|
|
|
|
|
For starters, you should never have to call in the garbage collector yourself: it only needs to be used when you start to run out of memory.
Second, that's really rather nasty code. The DataReceived event is started on a non-UI thread, as you know (or you wouldn't be Invoking the UI), but you are changing / using the value of SB on two threads, with no checking or locking to make sure that there isn't a problem. And you Invoke the UI thread even if there is no data to play with - and DataReceived can be fired for each character received, even if you have already removed them from the buffer.
You are also creating a new Font object (which is identical to the last) potentially for each character you receive, without any attempt to dispose of them. The GC will not do that, so Graphics Handles are being used up at a frightening rate - and these do not trigger the GC to do anything.
And there is a spurious ToString in there: Split returns an array of strings, so converting its constituent parts to a string is unnecessary.
Personally?
I'd have a background task processing the data with locking to prevent problems, and only invoke the bits which update the actual UI elements. I'd also use the same Font object for the label, and not change it at all.
And Application.DoEvents is a definite no-no!
I'd probably not use Split at all - it's not particularly efficient since it creates a lot of memory you aren't using. I'd look at IndexOf and SubString instead to "pull out" just the bit you are interested in. Even if I did use Split, you really, really need to check the number of array elements it returns: The DataReceived event doesn't wait for the end of your message before it "kicks in"...
[edit]Typos[/edit]
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
modified 22-Sep-15 5:06am.
|
|
|
|
|
Many thanks for the detailed answer !
If this is not hard, I'd be happy if you can change things problematic in this code.
|
|
|
|
|
OG has given you a detailed answer of the issues in your code, it shouldn't be too much trouble for you to convert it based off his reply. You might want to do this for yourself.
|
|
|
|
|
Just to add to what Pete said, I couldn't if I wanted to: I don't have access to the equipment you are connecting to, or any idea what the data looks like, or what's important about it - so I couldn't test any changes I did make!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
thanks for the help,
i change my code to:
private SerialPort port;
StringBuilder SB;
private void Recepcion(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SB = new StringBuilder(1000);
SB.Append(port.ReadLine());
port.DiscardInBuffer();
this.Invoke(new EventHandler(Actualizar));
}
catch { }
}
but still same problem..... my program fonts change alone for no reason.....
|
|
|
|
|
All you have done it take out the DoEvents and the Thread.Sleep.
You have done nothing about the problems I told you about.
And you are surprised that your code has the same fault?
Are you just guessing here, or have you designed this properly?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Maybe I'm not an expert like you,
I do my best.
Right now I have a problem and I'm really trying to solve it in all ways
|
|
|
|
|
I have around 100 Virtual Machines open in my Remote Desktop Connection Manager and I want to perform a same operation on all those machines. Can I do this using some code?
|
|
|
|
|
No idea. You haven't told us what operation you want to perform.
|
|
|
|
|
I have a Windows Desktop application opened on all the machines and I want to mark/unmark a checkbox.
|
|
|
|
|
I am compiling the c# code at run time using "Reflection" and trying to get the methods names. I am able to get the user defined methods and also predefined methods. But I want get the only the user defined methods.
My code :
Assembly assembly = results.CompiledAssembly;
var names = (from type in assembly.GetTypes()
from method in type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static)
select method.Name).Distinct().ToList();
Can any one help me.
Thanks in Advance.
|
|
|
|
|
If you don't want the "inherited" methods in there, then lookup its baseclass, find out which methods it has, and subtract those from the list you originally got.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Sounds good to me!
Might need to extract any interface methods as well, though.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks for you reply.
I have solved the my problem by using below solution
solution
**************
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
|
|
|
|
|
Try using 'GetMethod like this:
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
"Inherited members are not considered"
Nice
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|