Process.GetProcessesByName Doesn't work on exe - c#

if (!Main.isAttached)
{
num++;
if (num <= 15)
{
try
{
Main.gameProcess = Process.GetProcessesByName("csgo")[0];
if ((Main.gameProcess == null || !Main.IsModuleLoaded(Main.gameProcess, "client_panorama.dll") ? true : !Main.IsModuleLoaded(Main.gameProcess, "engine.dll")))
{
continue;
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
continue;
}
while (true)
{
if ((Main.clientPanoramaDll == null ? false : Main.engineDll != null))
{
break;
}
Thread.Sleep(100);
Main.clientPanoramaDll = Main.GetModuleHandle(Main.gameProcess, "client_panorama.dll");
Main.engineDll = Main.GetModuleHandle(Main.gameProcess, "engine.dll");
}
Main.isAttached = true;
}
else
{
MessageBox.Show("CSGO Not Open!", "Open the game first.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
base.Close();
break;
}
}
I am trying to program a mod for CSGO but it says it cannot detect the game is opened when it is already opened! I tried changing It to csgo.exe, csgo.exe32, but nothing works. Any tips please?

You didn't share with us your IsModuleLoaded() function so we can't answer this question, but here is the code I use which should solve your problem:
public static IntPtr GetModuleBaseAddress(Process proc, string modName)
{
IntPtr addr = IntPtr.Zero;
foreach (ProcessModule m in proc.Modules)
{
if (m.ModuleName == modName)
{
addr = m.BaseAddress;
break;
}
}
return addr;
}
Process proc = Process.GetProcessesByName("csgo")[0];
var modBase = ghapi.GetModuleBaseAddress(proc, "client.dll");
You can check the return value of GetModuleBaseAddress, if it's equal to IntPtr.Zero then the module was not loaded. It also will serve as the module handle, so you don't need additional redundant code.

Related

Weird results in c# app game

For an internship project I'm making an app based on Foley sound effects. I made a game for it. One button generates the effect, one plays the sound and four buttons for possible awnsers.
Somehow, the text displays ('helaas' and 'juist!') aren't consistent. The awnser could be right and it will display 'helaas', but when clicken multiple times, it will display 'juist!'. Can anyone help me with what I am doing wrong here?
int kiesnummer()
{
Random randomSound = new Random();
int theSound = randomSound.Next(1, 4);
return theSound;
}
NewSound.Click += delegate
{
kiesnummer();
if (kiesnummer() == 1)
{
welk.Text = "Open haard";
}
else if (kiesnummer() == 2)
{
welk.Text = "Regen";
}
else if (kiesnummer() == 3)
{
welk.Text = "Hondenpootjes op hout";
}
else if (kiesnummer() == 4)
{
welk.Text = "Paardenhoeven op beton";
}
};
Play.Click += delegate
{
if (kiesnummer() == 1)
{
_chips.Start();
}
else if (kiesnummer() == 2)
{
_rain.Start();
}
else if (kiesnummer() == 3)
{
_doggo.Start();
}
else if(kiesnummer() == 4)
{
_koko.Start();
}
};
//Parameters aan functie koppelen bij klikken op de knop
Aw1.Click += delegate
{
kiesknop(1);
};
Aw2.Click += delegate
{
kiesknop(2);
};
Aw3.Click += delegate
{
kiesknop(3);
};
Aw4.Click += delegate
{
kiesknop(4);
};
//Beoordelen of keuze juist of onjuist is
bool kiesknop(int knop)
{
if (knop == kiesnummer())
{
end.Text = "Juist!";
return true;
}
else
{
end.Text = "Helaas!";
return false;
}
}
(I left the button and media declerations out, since it didn't seem relevant)
Calling kiesnummer(); in every if condition will give you different results as it generates new random value every time.
Call it once and use its value through-out:
int value = kiesnummer();
if (value == 1)
{
welk.Text = "Open haard";
}
else if (value == 2)
{
welk.Text = "Regen";
}
else if (value) == 3)
{
welk.Text = "Hondenpootjes op hout";
}
else if (value == 4)
{
welk.Text = "Paardenhoeven op beton";
}

Visual Studio C# and Short-circuit evaluation

With the || Operator, Microsoft describes short circuit evaluation here Short Circuit Evaluation
However, I have the following code which seems to contradict this process:
if ((_opcLoaded || DoLoadOPC()) &&
(_tagsAdded || DoAddTags()) &&
DoWriteRecipe() &&
(DoResume()))
What I'm trying to prevent is the function DoAddTags from being called if _tagsAdded is true (DoAddTags sets _tagsAdded to true).
However, I'm finding that DoAddTags is called even when _tagsAdded is true. It's the same for _opcLoaded and DoLoadOPC. I've had to put a condition inside DoAddTags to check for _tagsAdded, which shouldn't be necessary.
Can someone explain why this is happening?
Here is the Complete Code
//
// Resume a Paused recipe
case MonitoredTasks.Resume:
Task.Factory.StartNew(() =>
{
MonitoredTask = MonitoredTasks.None;
if ((_opcLoaded || DoLoadOPC()) &&
**(_tagsAdded || DoAddTags())** &&
DoWriteRecipe() &&
(DoResume()))
{
MonitoredTask = MonitoredTasks.None;
RunningState = RecipeRunningStates.Running;
Status = CIPStatuses.Running;
}
else
{
MonitoredTask = MonitoredTasks.Resume;
}
});
break;
And the code for DoAddTags
/// <summary>
/// Adds all necessary tags to the OPC Server Manager
/// </summary>
/// <returns></returns>
bool DoAddTags()
{
bool result = false;
var oldActivity = Activity;
//
// Not doing anything OPC related?
if (Activity != CIPActivities.AddingOPCTags && !_tagsAdded && Activity != CIPActivities.StartingOPC)
{
lock (_locks[LOCK_OPC])
{
Activity = CIPActivities.AddingOPCTags;
Status = CIPStatuses.Initialising;
RecipeError = Errors.None;
try
{
//
// Reset connection and internal tags list
_serverManager.Reset();
//
// Now to add all OPC Tags - Area
CIPStatusTag = _serverManager.AddTag(_area.CIPStatusTag);
RecipeIDTag = _serverManager.AddTag(_area.RecipeIDTag);
RecipeInstructionIDTag = _serverManager.AddTag(_area.RecipeInstructionIDTag);
HandshakingTag = _serverManager.AddTag(_area.HandshakingTag);
GlobalInstructionIDTag = _serverManager.AddTag(_area.GlobalInstructionIDTag);
InstructionAttemptsTag = _serverManager.AddTag(_area.InstructionAttemptsTag);
//
// Area tags OK?
if (CIPStatusTag == null || RecipeIDTag == null || RecipeInstructionIDTag == null || HandshakingTag == null || GlobalInstructionIDTag == null || InstructionAttemptsTag == null)
{
RecipeError = Errors.InvalidAreaTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags - Invalid AREA Tags"), Sender = this });
}
else
{
VM_CIPInstruction vm = null;
bool instructionTagErrors = false;
//
// For each area instruction that is used, assig a link to the instruction
foreach (var i in _areaInstructions)
{
//
// Create a View Model for the specified area instruction : this allows us to determine the number of parameters (tags) that apply to the instruction
vm = new VM_CIPInstruction(i.Value.Instruction);
//
// Assign device reference tags
if (vm.DeviceReferencesAvailable)
{
i.Value.DeviceTag = _serverManager.AddTag(i.Value.Instruction.DeviceReferenceTag);
instructionTagErrors = i.Value.DeviceTag == null;
}
//
// For each required parameter, add tag
for (int paramNo = 1; paramNo <= vm.NoOfParams; paramNo++)
{
switch (paramNo)
{
case 1:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param1Tag >= 0)
{
i.Value.Param1 = _serverManager.AddTag(i.Value.Instruction.Param1Tag);
if (i.Value.Param1 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 2:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param2Tag >= 0)
{
i.Value.Param2 = _serverManager.AddTag(i.Value.Instruction.Param2Tag);
if (i.Value.Param2 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 3:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param3Tag >= 0)
{
i.Value.Param3 = _serverManager.AddTag(i.Value.Instruction.Param3Tag);
if (i.Value.Param3 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 4:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param4Tag >= 0)
{
i.Value.Param4 = _serverManager.AddTag(i.Value.Instruction.Param4Tag);
if (i.Value.Param4 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 5:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param5Tag >= 0)
{
i.Value.Param5 = _serverManager.AddTag(i.Value.Instruction.Param5Tag);
if (i.Value.Param5 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 6:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param6Tag >= 0)
{
i.Value.Param6 = _serverManager.AddTag(i.Value.Instruction.Param6Tag);
if (i.Value.Param6 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
}
}
if (instructionTagErrors)
{
RecipeError = Errors.InvalidInstructionTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage(String.Format("CIPRecipe.DoAddTags - Invalid Instruction {0} Tags", vm.Name)), Sender = this });
break;
}
}
//
// Any problems adding tags?
if (RecipeError == Errors.None)
{
Activity = CIPActivities.StartingOPC;
//
// Once all tags added, start OPC Server
result = _serverManager.Start();
if (!result)
{
Status = CIPStatuses.AddTagsFailed;
RecipeError = Errors.OPC;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags - Start of OPC failed"), Sender = this });
}
else
{
**_tagsAdded = true;**
Status = CIPStatuses.TagsAdded;
}
}
else
{
Status = CIPStatuses.AddTagsFailed;
}
}
}
catch (Exception ex)
{
RecipeError = Errors.Exception_AddTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags"), Exception = ex, Sender = this });
}
finally
{
Activity = oldActivity;
}
}
}
return Status == CIPStatuses.TagsAdded;
}
I've highlighted the relevant lines with **
On the first pass DoAddTags is executed and _tagsAdded set to TRUE- I've placed a breakpoint here, so I know it is being set. Shortly afterwards (with or without the former breakpoint) DoAddTags is again entered (on the first line) despite_doAddTags == true.
I've even set a breakpoint on the code "(_tagsAdded || DoAddTags())". _tagsAdded == true, yet DoAddTags is still entered.
So what I'm seeing is, and all the Watches/Debugging info is consistent with is that DoAddTags is being called whilst _tagsAdded == true
This code won't display the behavior you describe, the short-circuiting works just as described.
What actually happens: _tagsAdded is initially false, so DoAddTags() is called, which sets _tagsAdded to true.
Then the debugger kicks in, you inspect _tagsAdded and see it's true.
Instead step through your code using F11 and inspect or watch all relevant variables.

Deny USB arrival

I am working on USB Monitor in C# and I wanted to be able to react after the system driver processed arrival and enabled the arriving device, but faster than application level processes (Explorer). I wanted to examine device for autorun.inf and if found to DENY the arrival. I used BROADCAST_QUERY_DENY as described on MSDN but no success. Here is the code (assuming USB arrives as 'I' drive):
switch (msg.Msg)
{
case Win32CODES.WM_DEVICECHANGE:
{
if (msg.LParam != IntPtr.Zero)
{
DEV_BROADCAST_HDR pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_HDR));
switch ((int)msg.WParam)
{
case Win32CODES.DBT_DEVICEARRIVAL:
{
if (pHdr.dbch_devicetype == Win32CODES.DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME pVol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_VOLUME));
Char c = GetDriveLetter(pVol.dbcv_unitmask);
if (c == 'I')
{
msg.Result = new IntPtr(Win32CODES.BROADCAST_QUERY_DENY );
base.WndProc(ref msg);
return;
}
}
break;
}
}
}
break;
}
}
base.WndProc(ref msg);
}
Then I tried another way but again no success.
switch (msg.Msg)
{
case Win32CODES.WM_DEVICECHANGE:
{
if (msg.LParam != IntPtr.Zero)
{
DEV_BROADCAST_HDR pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_HDR));
switch ((int)msg.WParam)
{
case Win32CODES.DBT_DEVICEARRIVAL:
{
if (pHdr.dbch_devicetype == Win32CODES.DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME pVol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_VOLUME));
Char c = GetDriveLetter(pVol.dbcv_unitmask);
if (c == 'I')
{
int bytesReturned = 0;
IntPtr buffer = Marshal.AllocHGlobal(sizeof(int));
SafeFileHandle _hdev = CreateFileR(c.ToString());
bool result = DeviceIoControl(_hdev, CTL_CODE(0x00000033, 0x0400, 0, 1),
IntPtr.Zero, 0, buffer, sizeof(int),
out bytesReturned, IntPtr.Zero);
int sessionId = Marshal.ReadInt32(buffer);
Marshal.FreeHGlobal(buffer);
}
}
break;
}
}
}
break;
}
}
base.WndProc(ref msg);
Is there a way to accomplish this? Thanks..

Whats the problem in this function C#

I have written the below function to select a numeric string such as 1,23,000.00
In the WebBrowser I am trapping Double_Click Event and then passing the selected range to the below function.
lets say the initial selection was 000 and my target is to select the whole string as mentioned above.
myRange=doc.selection.createRange()
myRange=SelectCSNumbers(myRange)
I am returning a Range object from the below function. The issue here is
return tmpRange.duplicate();//here it should terminate
count++;
when I am returning the final range this method is getting called again
How I dont know, Can anyone pointout my mistake.
private mshtml.IHTMLTxtRange SelectCSNumbers(mshtml.IHTMLTxtRange myRange)
{
mshtml.IHTMLTxtRange tmpRange = myRange.duplicate();
string[] strInt = tmpRange.text.Split(',');
bool result = false;
result = CheckText(tmpRange, strInt, result);
if (result && count==0)//
{
//Expand the Range with a single Character
tmpRange.expand("character");
if (tmpRange.text.Length > myRange.text.Length)
{
if (tmpRange.text.IndexOf(' ') == -1) //if no space is found that means the selection is not proper
{
//Check for ,/.
if (tmpRange.text.IndexOf(',') == -1)//if NO Comma is found
{
if (tmpRange.text.IndexOf('.') == -1)
{
//EOS
}
else
{
//. is found
SelectCSNumbers(tmpRange.duplicate());
}
}
else
{
SelectCSNumbers(tmpRange.duplicate());
}
}
else if (tmpRange.text.IndexOf(' ') != -1)
{
tmpRange = myRange.duplicate();
tmpRange.moveStart("character", -1);
if (tmpRange.text.IndexOf(' ') == -1) //if no space is found that means the selection is not proper
{
//Check for ,/.
if (tmpRange.text.IndexOf(',') == -1)//if NO Comma is found
{
if (tmpRange.text.IndexOf('.') == -1)
{
//EOS
}
else
{
//. is found
SelectCSNumbers(tmpRange.duplicate());
}
}
else
{
SelectCSNumbers(tmpRange.duplicate());
}
}
}
}
else if (tmpRange.text.Length == myRange.text.Length)
{
tmpRange = myRange.duplicate();
tmpRange.moveStart("character", -1);
if (tmpRange.text.Length == myRange.text.Length)
{
//tmpRange = null;
return tmpRange.duplicate();//here it should terminate
count++;
}
else if (tmpRange.text.IndexOf(' ') == -1) //if no space is found that means the selection is not proper
{
if (tmpRange.text.IndexOf(',') == -1)//if NO Comma is found
{
if (tmpRange.text.IndexOf('.') == -1)
{
//EOS
}
else
{
//. is found
SelectCSNumbers(tmpRange.duplicate());
}
}
else
{
SelectCSNumbers(tmpRange.duplicate());
}
}
}
}
return tmpRange.duplicate();
}
This doesn't help immediately, but addresses a bigger problem
This code needs to be refactored. It will cause problems for you down the line. You have copy-pasted code that will be a pain to take care of. And also, it makes it harder for others to help.
Here is a suggestion for a refactoring (Not Tested)
private mshtml.IHTMLTxtRange SelectCSNumbers(mshtml.IHTMLTxtRange myRange)
{
mshtml.IHTMLTxtRange tmpRange = myRange.duplicate();
string[] strInt = tmpRange.text.Split(',');
bool result = false;
result = CheckText(tmpRange, strInt, result);
if (result && count==0)//
{
//Expand the Range with a single Character
tmpRange.expand("character");
if (tmpRange.text.Length > myRange.text.Length)
{
if (tmpRange.text.IndexOf(' ') == -1) //if no space is found that means the selection is not proper
{
SomeOtherFunction(tmpRange);
}
else if (tmpRange.text.IndexOf(' ') != -1)
{
tmpRange = myRange.duplicate();
tmpRange.moveStart("character", -1);
SomeOtherFunction(tmpRange);
}
}
else if (tmpRange.text.Length == myRange.text.Length)
{
tmpRange = myRange.duplicate();
tmpRange.moveStart("character", -1);
if (tmpRange.text.Length == myRange.text.Length)
{
//tmpRange = null;
return tmpRange.duplicate();//here it should terminate
count++;
}
else if (tmpRange.text.IndexOf(' ') == -1) //if no space is found that means the selection is not proper
{
SomeOtherFunction(tmpRange);
}
}
}
return tmpRange.duplicate();
}
private void SomeOtherFunction(mshtml.IHTMLTxtRange tmpRange)
{
if (tmpRange.text.IndexOf(',') == -1)//if NO Comma is found
{
if (tmpRange.text.IndexOf('.') == -1)
{
//EOS
}
else
{
//. is found
SelectCSNumbers(tmpRange.duplicate());
}
}
else
{
SelectCSNumbers(tmpRange.duplicate());
}
}
Random guess:
if (tmpRange.text.Length == myRange.text.Length)
{
count++;
return tmpRange.duplicate();
}
If you put count++ after the return statement, it will never be executed.

How do i prevent a StackOverflow error in the following code?

I have the follwing code that provides an auto refresh feature to a WCF Console Hosted Application.
When the Console.ReadKey accepts an invalid character, it restarts the ReadKey method. If the user mashes the keyboard long enough on this code it will go into a StackOverflowException.
Does anyone have a way to re-write this code so that it doesn't cause the stack to blow?
[STAThread]
static void Main(string[] args)
{
bool restart = true;
while(restart)
{
using (var myWcfHost = new MyWcfHost())
{
myWcfHost.start();
Console.WriteLine("Press Enter to quit or Ctrl+R to restart");
restart = WaitForRestart();
}
}
}
private static bool WaitForRestart()
{
// clear users input
Console.CursorLeft = 0;
Console.Write(' ');
Console.CursorLeft = 0;
// read users input
var key = Console.ReadKey();
if ((key.Modifiers & ConsoleModifiers.Control) != 0
&& key.Key == ConsoleKey.R)
{
// refersh the settings
ConfigurationManager.RefreshSection("appSettings");
return true;
}
if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
{
return false;
}
return WaitForRestart();
}
Replace recursion with a loop:
private static bool WaitForRestart()
{
while (true)
{
// clear users input
Console.CursorLeft = 0;
Console.Write(' ');
Console.CursorLeft = 0;
// read users input
var key = Console.ReadKey();
if ((key.Modifiers & ConsoleModifiers.Control) != 0
&& key.Key == ConsoleKey.R)
{
// refersh the settings
ConfigurationManager.RefreshSection("appSettings");
return true;
}
if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
{
return false;
}
}
}
It looks like each time there's an invalid key pressed, you push another WaitForRestart onto the stack, eventually resulting in an overflow exception. I think this would fix:
private static bool WaitForRestart()
{
// clear users input
Console.CursorLeft = 0;
Console.Write(' ');
Console.CursorLeft = 0;
while (true)
{
// read users input
var key = Console.ReadKey();
if ((key.Modifiers & ConsoleModifiers.Control) != 0
&& key.Key == ConsoleKey.R)
{
// refersh the settings
ConfigurationManager.RefreshSection("appSettings");
return true;
}
if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
{
return false;
}
}
}

Categories

Resources