|
Hmm, that is rather strange. Here is a quick work around.
private void ClearSelected()
{
CheckedListBox clb = null;
foreach(Control c in grp.Controls)
{
if(c is CheckedListBox)
{
clb = c as CheckedListBox;
if(clb != null)
{
foreach(int index in clb.CheckedIndices)
clb.SetItemChecked(index, false);
}
}
}
}
- Nick Parker My Blog | My Articles
|
|
|
|
|
Consider that you might have nested controls, that a CheckedListBox may not be a direct child of a GroupBox . Consider a generic recursive loop like so:
void ClearSelected(ControlCollection controls)
{
if (controls == null || controls.Count == 0) return;
foreach (Control control in controls)
{
if (control is CheckedListBox) ((CheckedListBox)control).ClearSelected();
ClearSelected(control.Controls);
}
} This will encounter any CheckedListBox at any depth in the parent/child hierarchy of controls.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles]
|
|
|
|
|
ISA? How old is this machine?!
Anyway, you're going to have to write your own devices drivers, in C++, to communicate with the hardware. C# is NOT good at this part! You can use C# as a higher level controller, providing a user interface to the functions of the board.
Like leppie said, you'll need the Windows Driver Development Kit. Start here[^]!
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
hi!
simply can't find a way to get the drive roots in c#. would be great if you could help.
thanks
thomas
|
|
|
|
|
.NET Framework 2.0 will add a new class, System.IO.DriveInfo , which can do this easily.
For now with .NET Framework 1.x, there are several ways. One is to use WMI with the System.Management namespace like so:
using System;
using System.Management;
class Test
{
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("select * from Win32_LogicalDisk");
ManagementObjectCollection objects = searcher.Get();
if (objects != null)
{
foreach (ManagementObject obj in objects)
Console.WriteLine(obj.Properties["DeviceID"].Value);
}
}
} You could also P/Invoke several native APIs, like GetLogicalDrives :
using System;
using System.Collections;
using System.Runtime.InteropServices;
class Test
{
static void Main(string[] args)
{
uint drives = GetLogicalDrives();
byte[] buffer = BitConverter.GetBytes(drives);
BitArray bits = new BitArray(buffer);
for (int i=0, j=65; i<bits.Count; i++, j++)
if (bits[i])
Console.WriteLine((char)j + ":");
}
[DllImport("kernel32.dll", SetLastError=true)]
static extern uint GetLogicalDrives();
} There's many ways, but I hope these two alternatives for .NET 1.x point you in the right direction.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles]
|
|
|
|
|
|
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles]
|
|
|
|
|
Does anybody know any example code of populating windows treeview control with hierarchical dataset?
I prefer C# but vb will also do it.
I found couple samples on this side, but one uses classes, and another delegate. Both seem overkill.
My hierarchy is 3 levels deep, and the number of rows are limited. I can afford to load the treeview at the form load time.
I have been putting together following pieces, but it failed to load the tree in the relationship I want.
Thanks for any help!
private void Form1_Load(object sender, System.EventArgs e)
{
string sSQL;
SqlCommand cmd = sqlCnPubs.CreateCommand();
cmd.CommandType=CommandType.Text ;
sSQL = "Select ID, Segment from Prod_Segments";
cmd.CommandText=sSQL;
SqlDataAdapter daSeg = new SqlDataAdapter();
daSeg.SelectCommand=cmd;
DataSet dsProd=new DataSet();
daSeg.Fill (dsProd, "Segments");
sSQL = "Select ID, Catagory, SegmentID from Prod_Catagories";
cmd.CommandText=sSQL;
SqlDataAdapter daCat = new SqlDataAdapter();
daCat.SelectCommand=cmd;
DataSet dsCatagories=new DataSet();
daCat.Fill (dsProd, "Catagories");
dsProd.Relations.Add("SegtoCat", dsProd.Tables["Segments"].Columns["ID"], dsProd.Tables["Catagories"].Columns["SegmentID"]);
foreach (DataRow rowSeg in dsProd.Tables["Segments"].Rows)
{
TreeNode nodeSeg = new TreeNode();
nodeSeg.Text=rowSeg["Segment"].ToString();
nodeSeg.ImageIndex=0;
tvwProd.Nodes.Add(nodeSeg);
foreach (DataRow rowCat in rowSeg.GetChildRows("SegtoCat"))
{
TreeNode nodeCat = new TreeNode();
nodeCat.Text=rowCat["Catagory"].ToString();
tvwProd.Nodes.Add(nodeCat);
}
}
|
|
|
|
|
Make sure that an enforced DataRelation or an assumed relationship exists in a DataTable within your DataSet , like ParentID -> ID. For the top-level rows, ParentID (in this example) should be NULL.
To begin, find the rows with a NULL ParentID using DataTable.Select('ParentID = NULL') . That gives you a DataRow[] array. For each DataRow you add a TreeNode to TreeView.Nodes and then pass DataRow.GetChildRows using a DataRelation (best way of doing it), or dynamically construct another WHERE clause to pass to DataTable.Select like I did above (except replacing NULL with the current row's ID).
In a recursive method you add a TreeNode for each row and repeat the steps above, passing them to the same method. This is recursion.
The way you're doing it is not recursive and will only work for a level or two. Besides, you shouldn't do this in the Form.Load event handler. This can be a very expensive call and the form will be delayed. Users expact fast results and will think your application has hung and will most likely try to kill it or just stop using it. Consider starting a new thread (and be sure to use Control.Invoke ) that does this so the form can load, optionally with user feedback like a ProgressBar while processing results.
Take a look at http://www.codeproject.com/script/comments/forums.asp?msg=745216&forumid=1649#xx745234xx[^] where I've explained this before in this forum.
Below is something similar to a method I used before to add TreeNode s to a TreeView safely. You should read the documentation for Control.Invoke in the .NET Framework SDK for more details:
private delegate int AddTreeNodeCallback(TreeNode node);
private void SafeAddTreeNode(TreeNodeCollection nodes, TreeNode node)
{
if (treeView1.InvokeRequired)
{
AddTreeNodeCallback cb = new AddTreeNodeCallback(nodes.Add);
treeView1.Invoke(cb, new object[] {node});
}
else nodes.Add(node);
} I really do recommend starting this in another thread and using this method to add the TreeNode . Since you can easily get the row count from your DataTable , you could easily update a ProgressBar , but you should use Control.Invoke still. Always use Control.Invoke when communicating with a control created on a different thread.
Finally, try to avoid refering to DataColumn s and DataRelation s by their string name. This is very expensive as many lookups are required. Use either an integer index or the actual DataColumn or DataRelation object, which is trivial when using a typed DataSet (from using xsd.exe or VS.NET to create a new DataSet schema, which is available when you right-click on a project and select Add->Add New Item->DataSet). You can also programmatically create one and refer to the two classes I mentioned above that you programmatically added to the named DataTable , which you add to a named DataSet . This results in much faster code.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles]
|
|
|
|
|
public ArrayList strline=new ArrayList();
strline.Add("I found a reason for me. To change who I used to be. A reason to start over new. And the reason is you.");
strline.Add("Anger dwells only in the bosom of fools - John F. Kennedy.");
I hoped this could be work. but it didn't.
I want to replace string[] with readed Line by Line in txt file.
and I know how to read line by line but string[] Length is fixed as initial.
so I tried apple ArrayList in string[] but it's not easy to me.
How can we treat this?
Help me please.
Image will remind us some feelings and if I can ask someone about a problem, that's not a bad life.
|
|
|
|
|
Try using System.Collections.Specialized.StringCollection instead. Otherwise you can just returned objects from the ArrayList to string manually, string myStr = (string)myArrayList[0];
Does that answer your question?
Judah Himango
|
|
|
|
|
Hello buddie,
I load one UserControl for example c1.ascx file using LoadControl() method into a placeholder everything is ok.
I load another one as c2.ascx using LoadControl() in the first one (c1.ascx) now all eventhandlers in c2 class except Page_Load() are disabled!!!
Why is that? an ASP.NET bug or something notable can solve it?
Thank u
- Den 2 Fly
---
"Art happens when you least expect it."
|
|
|
|
|
This is the C# forum. You should post your question here[^].
Charlie
if(!curlies){ return; }
|
|
|
|
|
|
I have a display (kind of NUnit stuff) with two RichTextBox displays.
Left one is test results / right box is original results showing green or red.
What I want to do:
If someone scrolls either window up or down the other window scrolls in concert as well.
Has anyone successfully attempted this?
Thanks,
Michael
This signature left intentionally blank
|
|
|
|
|
It's possible and quite easy. There are serveral articles here on CodeProject that describe this in various languages, and if you click "Search comments" you can search this message board where we've discussed this before as well.
One such article is Scrolling Around with the RichTextBox Control[^]. It's in VB.NET but mostly calls to the BCL and P/Invoke method (PostMessage , to be exact). You handle the scrolling events (or notification message sent to the native window handle (HWND ), which does make things easier) and post them to the message queue for another RichTextBox . Keep in mind that almost all the Windows Forms controls are just encapsulating native Common Controls, so windows messages are still sent/posted and handled by a window procedure (defined as Control.WndProc ).
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles]
|
|
|
|
|
Thanks Heath. This was more exciting than synchronized swimming. For those searching messages...here is the C# converted solution.
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using TestMultiScroll;
namespace TestMultiScroll
{
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components = null;
public System.Windows.Forms.RichTextBox RichTextBox1 = null;
public System.Windows.Forms.RichTextBox RichTextBox2 = null;
public System.Windows.Forms.RichTextBox RichTextBox3 = null;
private const int WM_HSCROLL = 0x114;
private const int WM_VSCROLL = 0x115;
private const int WM_MOUSEWHEEL = 0x20A;
private const int WM_COMMAND = 0x111;
private const int WM_USER = 0x400;
private const int SBS_HORZ = 0;
private const int SBS_VERT = 1;
private const int SB_THUMBPOSITION = 4;
private Subclass sClass1 = null;
private Subclass sClass2 = null;
private Subclass sClass3 = null;
public Form1()
{
InitializeComponent();
}
protected void Dispose(bool disposing)
{
if (disposing)
{
if ( !( (components == null)))
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.RichTextBox1 = new System.Windows.Forms.RichTextBox ();
this.RichTextBox2 = new System.Windows.Forms.RichTextBox ();
this.RichTextBox3 = new System.Windows.Forms.RichTextBox ();
this.SuspendLayout();
this.RichTextBox1.Location = new System.Drawing.Point (24, 24);
this.RichTextBox1.Name = "RichTextBox1";
this.RichTextBox1.Size = new System.Drawing.Size (128, 128);
this.RichTextBox1.TabIndex = 0;
this.RichTextBox1.Text = "RichTextBox1";
this.RichTextBox1.WordWrap = false;
this.RichTextBox2.Location = new System.Drawing.Point (160, 24);
this.RichTextBox2.Name = "RichTextBox2";
this.RichTextBox2.Size = new System.Drawing.Size (128, 128);
this.RichTextBox2.TabIndex = 1;
this.RichTextBox2.Text = "RichTextBox2";
this.RichTextBox2.WordWrap = false;
this.RichTextBox3.Location = new System.Drawing.Point (296, 24);
this.RichTextBox3.Name = "RichTextBox3";
this.RichTextBox3.Size = new System.Drawing.Size (128, 128);
this.RichTextBox3.TabIndex = 3;
this.RichTextBox3.Text = String.Empty;
this.RichTextBox3.WordWrap = false;
this.AutoScaleBaseSize = new System.Drawing.Size (5, 13);
this.ClientSize = new System.Drawing.Size (448, 174);
this.Controls.Add(this.RichTextBox3);
this.Controls.Add(this.RichTextBox2);
this.Controls.Add(this.RichTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.Load += new System.EventHandler (Form1_Load);
this.RichTextBox1.VScroll += new System.EventHandler (RichTextBox1_VScroll);
this.RichTextBox2.VScroll += new System.EventHandler (RichTextBox2_VScroll);
this.RichTextBox3.VScroll += new System.EventHandler (RichTextBox3_VScroll);
this.RichTextBox1.HScroll += new System.EventHandler (RichTextBox1_HScroll);
this.RichTextBox2.HScroll += new System.EventHandler (RichTextBox2_HScroll);
this.RichTextBox3.HScroll += new System.EventHandler (RichTextBox3_HScroll);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(System.Object sender,System.EventArgs e)
{
sClass1 = new Subclass(RichTextBox1.Handle);
sClass2 = new Subclass(RichTextBox2.Handle);
sClass3 = new Subclass(RichTextBox3.Handle);
this.sClass1.NativeWindowsEvent += new Subclass.WindowsEventHandler (sClass_WindowProcedure);
this.sClass2.NativeWindowsEvent += new Subclass.WindowsEventHandler (sClass_WindowProcedure);
this.sClass3.NativeWindowsEvent += new Subclass.WindowsEventHandler (sClass_WindowProcedure);
for (int i = 0; i <= 100; i++)
{
if (i % 4 == 0)
{
RichTextBox1.AppendText(" this is a longer string to force HScroll " + i + System.Environment.NewLine);
RichTextBox2.AppendText(" this is a longer string to force HScroll " + i + System.Environment.NewLine);
RichTextBox3.AppendText(" this is a longer string to force HScroll " + i + System.Environment.NewLine);
}
else
{
RichTextBox1.AppendText(" this is a string " + i + System.Environment.NewLine);
RichTextBox2.AppendText(" this is a string " + i + System.Environment.NewLine);
RichTextBox3.AppendText(" this is a string " + i + System.Environment.NewLine);
}
}
}
public void sClass_WindowProcedure(ref Message uMsg)
{
switch (uMsg.Msg)
{
case (WM_VSCROLL):
if (uMsg.HWnd.Equals(RichTextBox1.Handle))
{
ThumbScrollHandler(RichTextBox1, new RichTextBox[] {RichTextBox2, RichTextBox3}, ref uMsg);
}
if (uMsg.HWnd.Equals(RichTextBox2.Handle))
{
ThumbScrollHandler(RichTextBox2, new RichTextBox[] {RichTextBox1, RichTextBox3}, ref uMsg);
}
if (uMsg.HWnd.Equals(RichTextBox3.Handle))
{
ThumbScrollHandler(RichTextBox3, new RichTextBox[] {RichTextBox1, RichTextBox2}, ref uMsg);
}
break;
case (WM_HSCROLL):
if (uMsg.HWnd.Equals(RichTextBox1.Handle))
{
ThumbScrollHandler(RichTextBox1, new RichTextBox[] {RichTextBox2, RichTextBox3}, ref uMsg);
}
if (uMsg.HWnd.Equals(RichTextBox2.Handle))
{
ThumbScrollHandler(RichTextBox2, new RichTextBox[] {RichTextBox1, RichTextBox3}, ref uMsg);
}
if (uMsg.HWnd.Equals(RichTextBox3.Handle))
{
ThumbScrollHandler(RichTextBox3, new RichTextBox[] {RichTextBox1, RichTextBox2}, ref uMsg);
}
break;
}
}
private void ThumbScrollHandler(RichTextBox sender, RichTextBox[] receivers, ref Message uMsg)
{
sClass2.NativeWindowsEvent -= new Subclass.WindowsEventHandler(ref sClass_WindowProcedure);
foreach (RichTextBox receiver in receivers)
{
Message msg = Message.Create(receiver.Handle, uMsg.Msg, uMsg.WParam, uMsg.LParam);
sClass2.SendWndProc(ref msg);
}
sClass2.NativeWindowsEvent += new Subclass.WindowsEventHandler(ref sClass_WindowProcedure);
}
private void RichTextBox1_VScroll(object sender,System.EventArgs e)
{
VerticalScroll(RichTextBox1, new RichTextBox[2] {RichTextBox2, RichTextBox3});
}
private void RichTextBox2_VScroll(object sender,System.EventArgs e)
{
VerticalScroll(RichTextBox2, new RichTextBox[2] {RichTextBox1, RichTextBox3});
}
private void RichTextBox3_VScroll(object sender,System.EventArgs e)
{
VerticalScroll(RichTextBox3, new RichTextBox[2] {RichTextBox1, RichTextBox2});
}
private void RichTextBox1_HScroll(object sender,System.EventArgs e)
{
HorizontalScroll(RichTextBox1, new RichTextBox[2] {RichTextBox2, RichTextBox3});
}
private void RichTextBox2_HScroll(object sender,System.EventArgs e)
{
HorizontalScroll(RichTextBox2, new RichTextBox[2] {RichTextBox1, RichTextBox3});
}
private void RichTextBox3_HScroll(object sender,System.EventArgs e)
{
HorizontalScroll(RichTextBox3, new RichTextBox[2] {RichTextBox1, RichTextBox2});
}
private void VerticalScroll(RichTextBox sender, RichTextBox[] receivers)
{
int position = GetScrollPos(sender.Handle, SBS_VERT);
foreach (RichTextBox receiver in receivers)
{
PostMessageA(receiver.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * position, 0);
}
}
private void HorizontalScroll(RichTextBox sender, RichTextBox[] receivers)
{
int position = GetScrollPos(sender.Handle, SBS_HORZ);
foreach(RichTextBox receiver in receivers)
{
PostMessageA(receiver.Handle, WM_HSCROLL, SB_THUMBPOSITION + 0x10000 * position, 0);
}
}
[DllImport("user32.dll")]
private static extern int GetScrollPos(IntPtr hWnd, int nBar);
[DllImport("user32.dll")]
private static extern bool PostMessageA(IntPtr hwnd, int wMsg, int wParam, int lParam);
}
public class Subclass : System.Windows.Forms.NativeWindow
{
public event WindowsEventHandler NativeWindowsEvent;
public delegate void WindowsEventHandler(ref Message uMsg);
public Subclass(IntPtr pWindowHandle):base()
{
base.AssignHandle(pWindowHandle);
}
protected override void WndProc(ref System.Windows.Forms.Message uMsg)
{
base.WndProc(ref uMsg);
if (NativeWindowsEvent != null)
NativeWindowsEvent(ref uMsg);
}
public void SendWndProc(ref System.Windows.Forms.Message uMsg)
{
base.WndProc(ref uMsg);
}
}
}
This signature left intentionally blank
|
|
|
|
|
Many thanks for converting it,
http://www.codeproject.com/vb/net/VbNetScrolling.asp?df=100&forumid=83108&select=939107
Thanks again, for the work theRealCondor.
progload.
|
|
|
|
|
I have a component in which the ErrorProvider is defined upon initialization of the component as:
<br />
valueErrorProvider = new System.Windows.Forms.ErrorProvider();<br />
valueErrorProvider.SetIconAlignment (this, ErrorIconAlignment.MiddleRight);<br />
valueErrorProvider.SetIconPadding (this, 2);<br />
valueErrorProvider.BlinkRate = 1000;<br />
valueErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;<br />
<br />
components = new System.ComponentModel.Container();<br />
tltpInternal = new System.Windows.Forms.ToolTip(components);<br />
tltpInternal.ShowAlways = false;<br />
tltpInternal.InitialDelay = 250;<br />
tltpInternal.AutoPopDelay = 5000;<br />
tltpInternal.Active = false;
To set/clear the message I use the following:
private void SetErrorMessage(string msg)<br />
{<br />
this.valueErrorProvider.SetError(this, msg);<br />
tltpInternal.SetToolTip(this, msg);<br />
tltpInternal.Active = (msg.Trim().Length > 0);<br />
tltpInternal.ShowAlways = (msg.Trim().Length > 0);<br />
}
The problem is that the ErrorProvider symbol does not always show. The Tooltip is always populated as expected, the symbol just doesn't flash. If I select a different application and then go back to the application with the error, it begins to flash as expected.
Is there something I need to call to ensure the ErrorProvider will display?
|
|
|
|
|
hai
i am doing a project in which i need to trap the active window title after any event like mouse click, minimize,alt+tab,etc. I tried to use the cbt hooks but could not install a global hook. i learnt that i need to give the final parameter of SetWindowsHookEx as 0. But even then i could not install it. please help me.Urgent.
Advance Thanks to u.
|
|
|
|
|
|
The WH_CBT hooks execute in the context of the application in which the even occured...so you need to write them as a _standard_ dll so the target process can load them into its address space.
Only WH_JOURNALRECORD, WH_JOURNALPLAYBACK, WH_KEYBAORD_LL and WH_MOUSE_LL global hooks execute in the context of the hook installer app so only they are safe form .NET afaik.
'--8<------------------------
Ex Datis:
Duncan Jones
Merrion Computing Ltd
|
|
|
|
|
sorry i could not understand what u said.I am attaching the code that i tried please check out the error i have made and inform me.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.Text;
namespace ThreadSpecificMouseHook
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
static int hHook = 0;
public String WindowName;
public const int HCBT_ACTIVATE = 5;
public const int WH_CBT= 5;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
HookProc WindowHookProcedure;
[StructLayout(LayoutKind.Sequential)]
public class CBTACTIVATESTRUCT
{
public bool fMouse;
public int hWndActive;
}
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
IntPtr hInstance, int threadId);
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode,
Int32 wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowText(int hWnd, StringBuilder text, int count);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
///
/// Required designer variable.
///
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(88, 112);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(40, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1,
this.button1});
this.Name = "Form1";
this.Text = "Form1";
this.TopMost = true;
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public int WindowHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//CBTACTIVATESTRUCT myhook = (CBTACTIVATESTRUCT) Marshal.PtrToStructure(lParam,typeof(CBTACTIVATESTRUCT));
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
if (nCode == HCBT_ACTIVATE)
{
GetActiveWindow();
MessageBox.Show(WindowName);
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
if(hHook == 0)
{
WindowHookProcedure = new HookProc(WindowHookProc);
hHook = SetWindowsHookEx(WH_CBT,
WindowHookProcedure,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if(hHook == 0 )
{
MessageBox.Show("SetWindowsHookEx Failed");
return;
}
button1.Text = "UnHook Windows Hook";
}
else
{
bool ret = UnhookWindowsHookEx(hHook);
//If UnhookWindowsHookEx fails.
if(ret == false )
{
MessageBox.Show("UnhookWindowsHookEx Failed");
return;
}
hHook = 0;
button1.Text = "Set Windows Hook";
this.Text = "Windows Hook";
}
}
public void GetActiveWindow()
{
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow().ToInt32() ;
if (handle != this.Handle.ToInt32())
{
if ( GetWindowText(handle, Buff, nChars) > 0 )
{
WindowName= Buff.ToString();
}
}
}
}
}
advance thanks
|
|
|
|
|
Hi,
I think this a simple question but I have two computers that I want to be synchronized so I have attached a GPS to them so I can get the universal time (UTC). Then I want to set the local system time to the same as the resently read UTC time. I have tried with the DateTime class but I can only find read only methods there.
I hope someone can help me with this problem.
Thanks in a million
|
|
|
|
|
Try P/Invoking SetSystemTime as the following:
[Serializable, StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
[MarshalAs(UnmanagedType.U2)] public short Year;
[MarshalAs(UnmanagedType.U2)] public short Month;
[MarshalAs(UnmanagedType.U2)] public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)] public short Day;
[MarshalAs(UnmanagedType.U2)] public short Hour;
[MarshalAs(UnmanagedType.U2)] public short Minute;
[MarshalAs(UnmanagedType.U2)] public short Second;
[MarshalAs(UnmanagedType.U2)] public short Milliseconds;
}
[DllImport("kernel32.dll")]
static extern bool SetSystemTime(ref SYSTEMTIME time);
- Nick Parker My Blog | My Articles
|
|
|
|
|