Suppose i have a textfile which continuous to be updated with text, how can i display the contents in a textbox in windows form (in real-time)?
for example. this is the contents of log.txt:
connected, bla bla bla
disconnected, bla bla bla
PS: i want it to be displayed in textBox of Form1 (real time also) so everytime the text file has new text, the textbox displays it. Any ideas, pls help. thanks. also can u provide a sample working code. thanks
Use a FileSystemWatcher
Use the example on MSDN (see the link above) you can add a event handler to Changed Event
and update your textbox from there.
Just call Application.DoEvents(); once you've updated your text. But note that updating too often might cause flicker as well as slow down your overall processing. Also note that this is error prone if any drawing/update code causes updates/draws again (infinite recursion).
Edit: Read half the question ...
Add a FileSystemWatcher to watch for changes to the log file. However this is a very ineffective approach and depending on the settings used to write the log file you might be missing access rights and/or the file might update only when the application closes. If both processes are your own code and you're able to modify them, you should think about other possibilities (e.g. a simple "server" you can connect to using some telnet (or custom) client).
Insert a RichTextBox and a FilesystemWatcher, and a textbox or something else to store the path and filename of the text file you want to show. Now, go to the FilesystemWatcher_Changed (or whatever it's called) event. There you put an if that checks if the changed file is the one you want to be shown, and then RichTextBox.LoadFile(file).
What this is going to do is monitor the fileystsem (hard disk or any folder you specify), and every time a file has cha nged, it's going to check if it's the file that we're looking at. If it is, it's going to reload the file into the RichTextBox.
Don't forget to set the RaiseEvent and Path properties of the FilesystemWatcher.
Example:
string blaFile = "C:\TextFile.txt"; // The text file that we want to read.
private void FilesystemWatcher_Changed(....).... // The FilesystemWatcher_Changed event notifies us when a file on the monitored path (FilesystemWatcher.Path) has changed. When a file has changed the code within this event gets executed.
{
if (e.File == blaFile) // We check if the file that has chenged, is the one we want.
{
RichTextBox.LoadFile(blaFile); // It is! We load it into the RichtextBox again so that it's "up-to-date"!
}
}
I'm not completely sure about the e.File as I haven't used C# in a while now, but it's something like that.
It is not suggested to use text file, since there are two processes to access the file and you require real-time update.
Try to use NamePipeServerStream and NamePipeClientStream for two processes memory sharing.
Related
I'm having a strange issue that maybe being caused by my ignorance.
I have a treeview with an .AfterSelect and any time that i change the design of my form (in the deign view) the code gets removed for some reason.
here is my code
this.lstTreeView.AfterSelect += LstTreeView_AfterSelect; < this is the code that gets removed
this.lstTreeView.Location = new System.Drawing.Point(194, 56);
this.lstTreeView.Name = "lstTreeView";
this.lstTreeView.Size = new System.Drawing.Size(220, 498);
this.lstTreeView.TabIndex = 6;
this is the code that it allows to work.
private void LstTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TreeNode CurrentNode = e.Node;
string fullpath = CurrentNode.FullPath;
MessageBox.Show(fullpath);
NrDirSearch(fullpath);
}
if anyone can give me some advice on why the .AfterSelect is being removed that would be really helpful.
I suggest you:
in the windows form designer, click the tree view to select it
in the properties grid click the lightning bolt and scroll to find the AfterSelect event
right click the name AfterSelect and choose reset
hit save all
Close out of the soution entirely/shut down visual studio
restart/reload the solution
Go back to the AfterSelect event as above, the box for which should be empty
click the drop down and choose your existing event handler
save all, quit and restart vs and check that the setting stayed
If you're finding it didn't stick, check that you don't have your designer open in another program e.g. A text editor that keeps autosaving an old version of the file that lacks the event handler?
Incidentally, the above process is how you add event in Design view - click the relevant control, lightning bolt, scroll to event wanted, double click the name of the event and you will be transported to your own code behind with a new named eventhandler created and ready to be filled
If you don't write any code in it, and go back to the designer and Reset the event as per the bulleted list instructions then your event handler method in your code will disappear. If you write code into the event handler then it is not removed when doing a reset, only empty handler methods are removed during reset
Side note: be careful with Undo if you see a message saying something like "performing this undo will cause a loss of work elsewhere" it usually indicates that the windows form design or designer.cs code will change as a result of actioning the undo
Designer files are safe to edit manually and it's sometimes necessary if the contents have gotten into a state where they are crashing the designer. I most often encounter this when deleting event handler s from my code that are still referenced in the designer. A screen appears saying a problem is preventing the forms designer from appearing, indicating the error line in the designer file. I have additionally in the past edited the designer directly to set large numbers of properties without the faff of using the designer - be mindful not to have a windows forms designer open at the same time as editing the designer.ca file because the forms designer will probably overwrite your changes. So long as you keep in mind that opening the same file in any two different editors at the same time can lead to conflict and loss of work, and take steps to ensure that edits in one editor are reflected in another before proceeding with further edits in the other editor, you'll be fine :)
Edit: having said that paragraph above, Mickey D made me realise an important point I'd overlooked:
The designer.cs file is read by the forms designer and uses to build the contents of the form, buttons, properties etc. As such if you are going to edit the designer.cs in a text editor you should limit your edits to only those things the forms designer can make use of, understand, represent and preserve when it next writes the file. Adding a line to set a button to enabled is fine. Removing a line that is causing it to crash is also good. Putting 27 methods that implement your entire program's database access strategy in is not a good idea as it will not be heeded or used to build the form when the designer reads the file and hence lost when the designer writes the file. If you're unsure of the difference between what will and won't be preserved stick to removing or fixing existing lines only rather than adding new lines of code
You should never[1] modify *.designer.cs files. They are code generated. Any changes you make are subject to being overwritten.
Instead either use the WinForms GUI Forms Designer to visually setup event handlers or you can do so in code in your form’s code-behind .cs file.
There are plenty of resources on the Net on how to use the WinForms designer.
[1] see Caius Jard's comment below for an exception to the rule that I concur with
I'm trying to save images from clipboard. This works well, if I copy something from Paint for example. If I take a screenshot, the Clipboard.GetContent().AvailableFormats shows me 0 items - so no Bitmap Image.
But when I put a timer for 1ms which gets the clipboard data, everything works fine. Since I think depending on random time is dirty, I would like to call something like WaitForClipboard.
Any ideas?
I think you could achieve it by handle clipboard update event. You could reference the below link for how to handle clipboard event.
Clipboard event C#
In the handler of clipboard update event, you could use the Clipboard.GetContent().AvailableFormats to check for available content.
In my application, I have a textbox. I want to be able to copy text from a webpage or document open elsewhere in Windows by simply highlighting the text and pressing a global hotkey - then have that text appear in the textbox.
What I am stuck on is the selection part: I'm looking for a way to use the selected text as a variable within my WPF application, but I can't seem to get access to it in a way that makes sense.
Right now, I'm working with the clipboard and Clipboard.GetText() to get my variable :
private void OnHotKeyHandler(HotKey hotKey) {
if (Clipboard.ContainsData(DataFormats.Text))
tb_number.Text = Clipboard.GetText();
}
But i'm trying to avoid a tedious CTRL-C each time i want to get this value and work with selected text, rather than copied text. Any ideas how I can do this on-select rather than by accessing the clipboard?
I beleive the question is much clearer now. Thanks for the editing.
I dont think you can modify the clipboard functionality thru a .NET application in an easy way. But you may get what you need with a third party application for windows called autohotkey.
http://www.autohotkey.com/docs/Tutorial.htm#Send
https://superuser.com/questions/166270/change-ctrl-x-c-and-v-hotkeys-in-windows-to-different-keys
i have a question about the moving file event on filesystemwatcher class , i`d like to stop the moving of file or edit it when the moving file event arises for a certain file , is that possible to handle inside the moving event ?
No, there is no way to stop someone moving or renaming a file using the FileSystemWatcher class.
If you look, none of the event arguments passed by the events on the FileSystemWatcher class have a Cancel property. Also, the fact that the class is simply called a Watcher is a bit of a clue.
You might consider using Access Control Lists to make sure someone cannot delete a file (since a move is really just a copy/delete). Or perhaps you could try opening a FileStream on the file so that you have it locked.
You cannot directly "cancel" the operation by means of the event handler. You would have to provide a compensating operation to programatically "undo" any changes you want undone.
You only receive the events after the fact has happened. It's a mere notification, not an event you'd have to approve. This can also be guessed from the missing Cancel or Handled property in the FileSystemEventArgs (as opposed to, for example, the KeyEventArgs) class.
You can detect a move and try to move the file back, based on the OldFullPath property of the RenamedEventArgs you receive.
This might however be confusing to your users or to other software. And try not to end up in an infinite loop, where you move the file back and forth every time you receive the event.
Please guide me as how to save/discard values of controls of a form, upon pressing Ok/Cancel button accordingly in Visual Studio C#?
Controls in a form include TablelayoutPanel(TextBoxes), NumericUpDown.
Need your expert guidance
Regards
Asad
With both of your buttons, inside the "onclick" event, call a function that will save the content of the form. You also need this call in the "onclose" event of the form, in case the user presses the top-right X button (or not, if you dont want data to be saved at that moment)
Inside that function, you will need some code that will save data to the registry.
Writing in the registry is easy. This webpage also explain how to get the data back. The values you will write will be the textbox.Value and such
The question isn't clear, but in a WinForm you can call
this.Close()
on the Click event of your Close button.
Every object or variable used by the form will be destroyed. Be careful! running background threads will still be alive until they terminate.
About saving the status of your variables it completely depends on what you need to with them after; you can either keep them in memory and pass them around like parameters or write on a disk (maybe with serialization?).
We need to know more.
edit
You may want to take a look at Application Configuration ( http://msdn.microsoft.com/en-us/library/ms184658(VS.80).aspx ).